/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-02 09:14:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /TracerMethodology_PC/src/pages/UserMana/index.js
 */

import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm, Table, Space, Cascader } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, ProFormText, ProFormSelect, ProFormDependency, LightFilter, ProFormDatePicker } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
// import CAUpload from '@/components/CAUpload';
import { getAccountingSubjectList, editAccountingSubjectList, delAccountingSubject, addAccountingSubject, getAccountingSubjectForSelecter } from './service';
import { idText } from 'typescript';
// import { getApportionmentLevelListNoPage } from '../apportionmentLevel/service';




const AccountingSubject = () => {
  const columns = [
    {
      title: '会计科目名称',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: false,
      width: '30%'
    },
    {
      title: '会计科目编码',
      dataIndex: 'accountingCode',
      key: 'accountingCode',
      hideInSearch: true,
      width: '30%'
    },
    {
      title: '是否固定成本',
      dataIndex: 'isBaseCost',
      key: 'isBaseCost',
      hideInSearch: true,
      render: (text) => <>{text == 1 ? '是' : '否'}</>,
      width: '20%'
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      key: 'option',
      width: '15%',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true)
          }}
        >
          添加
        </a>,
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();  //表格
  const ref = useRef();   //新增表单
  const [currentRow, setCurrentRow] = useState({});
  const [selectedLevelList, setSelectedLevelList] = useState(null); //类型
  const [selectedLevel, setSelectedLevel] = useState(null);
  const [accountType, setAccountType] = useState(1);
  const [options, setOptions] = useState([]);
  const [selectedAccountingSubject, setSelectedAccountingSubject] = useState([]);
  const [ifChild, setIfChild] = useState(false);
  const [expanedRowIds,setExpanedRowIds] = useState([]);


  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {
    handleUpdateModalVisible(bool);
    setIfChild(false);
    if (!bool) setCurrentRow(undefined);
  };



  //获取科室列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getAccountingSubjectList({ ...params, accountType: accountType });
    // console.log({res});
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delListHandler = async (value) => {
    const resp = await delAccountingSubject(value);
    if (resp.status == 200) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  const expandHandle = id=>{
    console.log({id,expanedRowIds});
    if(expanedRowIds.includes(id)){
      const temp = expanedRowIds;
      temp.splice(temp.findIndex(item => item == id), 1);
      setExpanedRowIds([...temp])
    }else{
      setExpanedRowIds([...expanedRowIds,id])
    }
  }
  

  /**
   * 
   * @param {Object} record  record对象
   * @param {String} type  可选值[del,edit,‘add’]
   */
  const customRowUpdata = (record,type)=>{
      //  console.log({record});
       const {accountingCode,accountingName,id} = record;
       const needRowData = {accountingCode,accountingName,id};
       setIfChild(true);
       setCurrentRow(needRowData);
    
       if(type == 'add')handleModalVisible(true);
       if(type == 'edit')handleUpdateModalVisible(true);
       if(type == 'del')delListHandler(needRowData);
  }

  //展开table
  const expandedRowRender = (record, index, indent, expanded) => {
    // console.log({ record, index, indent, expanded });
    const { child } = record;
    const _columns = columns.filter(item => !(['id', 'option'].includes(item.key)));

    return (<table>
      <tbody>
        {
          child&&child.map((item, index) => {
            const { accountingCode, accountingName, id, child } = item;
            console.log({ accountingCode, accountingName, id, child });
            return (
              <React.Fragment  key={index}>
                <tr key={id} style={{ position: 'relative' }}>
                  <td>
                    <table>
                      <tbody>
                      <tr>
                        <td style={{ position: 'absolute', width: 0 }}>
                          {
                            child&&child.length > 0 &&(
                              <button onClick={()=>expandHandle(id)} style={{top:12}} className={
                                expanedRowIds.includes(id)?'ant-table-row-expand-icon ant-table-row-expand-icon-expanded':'ant-table-row-expand-icon ant-table-row-expand-icon-collapsed'
                              }></button>
                            ) 
                          }
                          {/* <button className="ant-table-row-expand-icon ant-table-row-expand-icon-expanded customExpandIcon"></button> */}
                        </td>
                        <td width="30%" style={{ paddingLeft: '0.8%',paddingTop:10,paddingBottom:10 }}><span style={{transform:'rotateY(180deg)'}}>↵</span>会计科目名称：{accountingName}</td>
                        <td width="30%" style={{ paddingLeft: '0.3%' }}>会计科目编码：{accountingCode}</td>
                        <td width="20%" style={{ paddingLeft: '0.7%' }}>否</td>
                        <td width="15%" style={{ paddingLeft: '0.9%' }}>
                          <a onClick={()=>customRowUpdata(item,'add')}>添加</a>
                          <a onClick={()=>customRowUpdata(item,'edit')}>编辑</a>
                          <a onClick={()=>customRowUpdata(item,'del')}>删除</a>
                        </td>
                      </tr>
                      </tbody>
                    </table>
                  </td>
                </tr>
                {
                  expanedRowIds.includes(id)&&<tr key={`expand${id}`}>
                  <td width="100%">
                    <table>
                      <tbody>
                        {
                          child.map((data, index) => {
                    
                            const { accountingCode, accountingName, id, child } = data;
                            return (
                              <tr key={id} style={{ position: 'relative' }}>
                                <td style={{ position: 'absolute', width: 0 }}>
                                  {
                                   child&&child.length > 0 && <button  class="ant-table-row-expand-icon ant-table-row-expand-icon-collapsed"></button>
                                 }
                                </td>
                                <td width="30%" style={{ paddingLeft: '2.5%',paddingTop:10,paddingBottom:10 }}>↵会计科目名称：{accountingName}</td>
                                <td width="30%" style={{ paddingLeft: '0.3%' }}>会计科目编码：{accountingCode}</td>
                                <td width="20%" style={{ paddingLeft: '0.7%' }}>否</td>
                                <td width="15%" style={{ paddingLeft: '0.9%' }}><a >编辑</a></td>
                              </tr>
                            )
                          })
                        }
                      </tbody>
                    </table>
                  </td>
                </tr>
                }
              </React.Fragment>
            )
          })
        }
      </tbody>
    </table>
    )
    
  };
   
  const onTabChange = (key)=>{
    console.log({key});
    setAccountType(Number(key));
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }

  useEffect(async () => {
    const respForSelecter = await getAccountingSubjectForSelecter();
    if (respForSelecter.status == 200) {
      setOptions(respForSelecter.data);
    }
  }, [])

  return (
    <PageContainer
    tabList={[
      {
        tab: '收益',
        key: 1,
      },
      {
        tab: '支出',
        key: 2,
      },
    ]} 
    onTabChange={onTabChange}  
    >

      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        expandable={{defaultExpandedRowKeys:[]}}
        // expandable={{ expandedRowRender }}
        toolbar={{
          actions: [
            
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                handleModalVisible(true);
              }}
            >
              新增
            </Button>
          ],
        }}
        search={false}
        pagination={{
          pageSize: 10,
        }}
      />

      <ModalForm
        title="新增会计科目"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        onVisibleChange={(bool) => {
          console.log({ currentRow });
          if (ref.current) {
            ref.current.resetFields();
          }
          setIfChild(false);
          handleModalVisible(bool);
        }}
        formRef={ref}
        onFinish={async (value) => {
          const { id } = currentRow;
          const success = await addAccountingSubject({ ...value, id: id ? id : 0,accountingType:accountType });
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
       

        <ProFormText
          label="会计科目编码"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.accountingCode" defaultMessage="会计科目编码是必填项" />
              ),
            },
          ]}
          width="sm"
          name="accountingCode"
        />
        <ProFormText
          label="会计科目名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.accountingName" defaultMessage="会计科目名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="accountingName"
        />
        {/* <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.accountingType" defaultMessage="请选择会计科目类型" />
              ),
            },
          ]}
          options={[
            {
              value: 1,
              label: '收入',
            },
            {
              value: 2,
              label: '支出',
            },
          ]}
          width="sm"
          name="accountingType"
          label="会计科目类型"
        /> */}
        <ProFormSelect
          rules={[
            {
              required: false,
              message: (
                <FormattedMessage id="pages.searchTable.isBaseCode" defaultMessage="请选择" />
              ),
            },
          ]}
          options={[
            {
              value: 0,
              label: '不是',
            },
            {
              value: 1,
              label: '是',
            },
          ]}
          width="sm"
          name="isBaseCode"
          label="是否固定成本"
        />
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          console.log({ '编辑': value });
          const success = await editAccountingSubjectList({...value,accountType});

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default AccountingSubject;
