/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-09-10 09:20:09
 * @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,Tag } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { ModalForm, DrawerForm, ProFormSelect, ProFormTextArea, ProFormDigit, ProFormText } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import UpdateFormDrawer from './updateForm_drawer';
// import CAUpload from '@/components/CAUpload';
import DrawerContent from './selectCopyDrawer';
import { getAccountingSubjectList } from '../accountingSubject/service';
import {
  getCostshareparamConnectList, editCostshareparamConnectList, delCostshareparamConnect,
  addCostshareparamConnect, getResponsibilityCenterSelecterList, getAccountingSubjectForSelecter,
  getHasSetParamsList, getParamsSelectableList, saveParamsList, copyParamsList,getCopyableToList
} from './service';

import {deepGetAllParents} from '@/utils';


const CostAllocationParamsConnect = () => {
  const columns = [

    {
      title: '分摊级别',
      dataIndex: 'shareLevel',
      key: 'shareLevel',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '责任中心编码',
      dataIndex: 'responsibilityCode',
      key: 'responsibilityCode',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '责任中心名',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      ellipsis: true,
      hideInSearch: false,
      render:(_,record) => {
             const {isShareCost,responsibilityName} = record;
             return isShareCost==1?<Tag color="default">{`${responsibilityName}(含)`}</Tag>:`${responsibilityName}`
      }
    },
    {
      title: '会计科目名称',
      dataIndex: 'accountingNames',
      key: 'accountingName',
      hideInSearch: true,
      ellipsis: true,
      
    },
    {
      title: '会计科目编码',
      dataIndex: 'accountingCodes',
      key: 'accountingCode',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '别名',
      dataIndex: 'alias',
      key: 'alias',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'costNode',
      key: 'costNode',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width:'18%',
      render: (_, record) => [
        <a
          key="config1"
          onClick={() => {
            setDrawerVisible(true);
            setCurrentRow(record);
            setCurrentResponsibilityRow(record);
          }}
        >
          分摊参数设置
        </a>,
        <a
          key="config1"
          onClick={() => {
            setCurrentRow(record);
            setDrawerType(1);
            setCopySelectDrawerVisible(true);
          }}
        >
          复制
        </a>,
        <a
          key="config2"
          onClick={() => {
            setEdit(true);
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];


  const drawerTableColumns = [
    {
      title: '分摊参数编码',
      dataIndex: 'shareParamCode',
      key: 'shareParamCode',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
      key: 'shareParamName',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '分摊比例',
      dataIndex: 'shareParamPopout',
      key: 'shareParamPopout',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config2"
          onClick={() => {
            setDrawerUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            setCurrentRow(record);
            delParamsListHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },

  ];


  const responsibilityColumns = [
    {
      title: '责任中心Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '责任中心名',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      hideInSearch: false,
      ellipsis: true,
    }
  ]

  const accountSubjectColumns = [
    {
      title: '会计科目Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: false,
      ellipsis: true,
    },
    {
      title: '会计科目名名',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: false,
      ellipsis: true,
    }
  ]

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [cascaderOptions, setCascaderOptions] = useState([]);
  const actionRef = useRef(); //表格
  const ref = useRef();   //新增表单
  const [currentResponsibilityRow, setCurrentResponsibilityRow] = useState({});

  const [currentRow, setCurrentRow] = useState(undefined);
  const [ifDisable, setIfDisable] = useState(false);
  const [selectedResponsibilityId, setSelectedResponsibilityId] = useState(null);
  const [selectedResponsibility, setSelectedResponsibility] = useState(null);

  const [copySelectDrawerVisible, setCopySelectDrawerVisible] = useState(false);

  const [drawerType, setDrawerType] = useState(0);  //1 复制数据  2  新增选择会计科目
  const [accountType, setAccountType] = useState(2); // 1 收入 2  支出

  const [edit,setEdit] = useState(false);


  const drawerFormRef = useRef(); //DrawerForm
  const actionDrawertableRef = useRef(); //Drawertable
  const drawerModalRef = useRef(); //DrawerModal
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerMadalVisible, setDrawerMadalVisible] = useState(false);
  const [hasSetParamsList, setHasSetParamsList] = useState([]);
  const [selectedParam, setSelectedParam] = useState(null);
  const [newAddParamList, setNewAddParamList] = useState([]);

  const [drawerUpdateModalVisible, setDrawerUpdateModalVisible] = useState(false);

  const [expandedRowKeys,setexpandedRowKeys] = useState([]);

  const [selectedAccountSubjects,setSelectedAccountSubjects] = useState([]);
  const updateFormRef = useRef();


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

  const drawerUpdateModalVisibleChange = (bool) => {
    setDrawerUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  }

  //获取科室列表
  const getList = async (params = {}, sort, filter) => {

    const res = await getCostshareparamConnectList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

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

  /**
   * 
   * @param {Object} record 表格行数据
   */
  const delParamsListHandler = (record) => {
    const { id } = record;
    const arr = hasSetParamsList;
    arr.splice(arr.findIndex(item => item.id === id), 1);
    setHasSetParamsList([].concat(arr));
    if (actionDrawertableRef.current) {
      actionDrawertableRef.current.reload();
    }
  }


  //分摊参数回调
  /**
   * 
   * @param {Boolean} bool 
   */
  const drawerVisibleChange = async (bool) => {
    // console.log({currentRow});
    if (bool) {
      //展示
      const { id } = currentRow;
      const resp = await getHasSetParamsList({ id });
      const { data, msg, status } = resp;
      // console.log({data, msg, status});
      if (status == 200) {
        setHasSetParamsList(data ? data : []);

        if (actionDrawertableRef.current) {
          actionDrawertableRef.current.reload();
        }
      }
    }
    setDrawerVisible(bool);
  }


  /**
   * 
   * @param {Boolean} bool 
   */
  const handleDrawerModalVisible = (bool) => {
    setDrawerMadalVisible(bool);
  }


  const getCopyableTableList = async () => {
    const {id:accountShareId} = currentRow;
    const resp = await getCopyableToList({accountShareId});
    const { status, data} = resp;
    if (status == 200) {
      return {
        data: data,
        total:data.length ,
        success: true
      }
    }
  }

  const getAccountingSubjects = async (params = {}, sort, filter) => {
    const resp = await getAccountingSubjectList({...params,accountType });
    const { status, data: { list, totalCount } } = resp;

    let accountingIdList=undefined;
    
    currentRow&&(accountingIdList = currentRow.accountingIdList)

    const defaultSelected = accountingIdList?accountingIdList.map(item=>Number(item)):[];
    // console.log({defaultSelected});
    setSelectedAccountSubjects(defaultSelected);
    const allParents = deepGetAllParents(list,'children');
    const ids = allParents?allParents.map(item=>item.id):[];
    setexpandedRowKeys(ids);
    if (status == 200) {
      return {
        data: list,
        total: totalCount,
        success: true
      }
    }
  }

  const selectAccountSubjecthandle = () => {
    setDrawerType(2);
    setCopySelectDrawerVisible(true);
  }

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

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setEdit(false);
              handleModalVisible(true);
            }}
          >
            新增
          </Button>
        ]}
        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}
      />

      <ModalForm
        title="新增成本分摊参数对应"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        formRef={ref}
        onVisibleChange={(bool) => {
          if (ref.current) {
            setIfDisable(false);
            ref.current.resetFields();
          }
          handleModalVisible(bool);
        }}
        onFinish={async (value) => {
          // console.log({value});
          // console.log(ref.current.getFieldsValue(true));
          const { costNode,isShareCost=1,alias} = value;
          const { accountingIds } = ref.current.getFieldsValue(true);
          const { responsibilityCode, responsibilityId, responsibilityName, shareLevel } = selectedResponsibility;

          const success = await addCostshareparamConnect({
            responsibilityId: selectedResponsibilityId,
            accountingIds: accountingIds,isShareCost,alias,
            costNode, responsibilityName, shareLevel, responsibilityCode
          });
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);
            
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择责任中心',
            },
          ]}
          fieldProps={{//这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
            onChange: async (val) => {
              setSelectedResponsibilityId(val);
              const resp = await getResponsibilityCenterSelecterList();
              const { data, msg, status } = resp;
              if (status == 200) {
                const selected = data.filter(item => item.id == val);
                setSelectedResponsibility(selected[0]);
                if (selected && selected[0].calcType == 1) {
                  setIfDisable(false);
                } else {
                  setIfDisable(true);
                }
              }
            },
          }}
          request={async () => {
            const resp = await getResponsibilityCenterSelecterList();
            const { data=[], msg, status } = resp;
            if (status == 200) {
              return data.map(item => ({
                label: item.responsibilityName,
                value: item.id
              }))
            }
          }}
          width="sm"
          name="responsibilityId"
          label="请选择责任中心"
        />
        <ProFormText
          disabled={ifDisable}
          rules={[
            {
              required: ifDisable?false:true,
              message: '请选择会计科目',
            },
          ]}
          fieldProps={{
            onClick: () => selectAccountSubjecthandle()
          }}
          width="sm"
          name="accountingName"
          label="选择会计科目"
        />
        <ProFormSelect
          disabled={ifDisable}
          rules={[
            {
              required: ifDisable?false:true,
              message: '请选择',
            },
          ]}
          width="sm"
          request={async () => [
            { label: '不包含分摊成本', value: 0 },
            { label: '包含分摊成本', value: 1 }
          ]}
          name="isShareCost"
          label="是否包含分摊成本"
        />
        <ProFormText
          width="sm"
          name="alias"
          label="别名"
        />
        <ProFormTextArea
          name="costNode"
          label="备注"
          width={300}
          placeholder="请输入备注"
        />
      </ModalForm>

      {/* 成本分摊参数设置 */}
      <DrawerForm
        title="分摊参数设置"
        formRef={drawerFormRef}
        visible={drawerVisible}
        onVisibleChange={(visible) => drawerVisibleChange(visible)}
        // onFinish={(value) => onSubmit({ ...values, ...value })}
        onFinish={async () => {
          if (true) {
            const { id } = currentResponsibilityRow;

            const resp = await saveParamsList({
              id,
              shareParamProportionVOList: hasSetParamsList
            });
            const { status } = resp;
            if (status == 200) {
              setDrawerVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }

        }}
      >
        <ProTable
          columns={drawerTableColumns}
          rowKey="id"
          actionRef={actionDrawertableRef}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setDrawerMadalVisible(true);
                setCurrentRow(undefined);
              }}
            >
              新增
            </Button>
          ]}
          request={async (params = {}, sort, filter) => {
            // console.log({ hasSetParamsList });
            return {
              data: hasSetParamsList,
              success: true
            };
          }}
          pagination={false}
          search={false}
        />
        <ModalForm
          title="新增分摊参数"
          width="800px"
          labelCol={{ span: 5, offset: 3 }}
          layout={'horizontal'}
          visible={drawerMadalVisible}
          formRef={drawerModalRef}
          onVisibleChange={(bool) => {
            if (drawerModalRef.current) {
              drawerModalRef.current.resetFields();
            }
            handleDrawerModalVisible(bool);
          }}

          onFinish={async (value) => {
            // console.log({ '新增分摊参数': value, selectedParam,hasSetParamsList});
            const { shareParamPopout } = value;
            const { id, shareParamCode, shareParamName } = selectedParam;

            setHasSetParamsList(hasSetParamsList.concat([{
              id, shareParamCode, shareParamName, shareParamPopout
            }]));

            setNewAddParamList(newAddParamList.concat([{
              id, shareParamCode, shareParamName, shareParamPopout
            }]));

            setDrawerMadalVisible(false);

            if (actionDrawertableRef.current) {
              actionDrawertableRef.current.reload();
            }
          }}
        >
          <ProFormSelect
            rules={[
              {
                required: true,
                message: '请选择责任中心',
              },
            ]}

            fieldProps={{//这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
              onChange: async (val) => {
                // setSelectedParam(val);
                const { id } = currentResponsibilityRow;
                // console.log({currentResponsibilityRow});
                const resp = await getParamsSelectableList({ id });
                const { data:{list=[]}, status } = resp;
                // console.log({resp});
                if (status == 200) {
                  const selected = list.filter(item => item.id == val);
                  console.log({ selected });
                  setSelectedParam(selected[0]);
                }
              },
            }}

            request={async () => {
              const { id } = currentResponsibilityRow;
              const resp = await getParamsSelectableList({ id });
              const { data:{list=[]}, status } = resp;
              // console.log({ resp });
              if (status == 200) {
                const temp = list.map(item => ({
                  label: item.shareParamName,
                  value: item.id
                }));
                return temp;
              }

            }}
            width="sm"
            name="id"
            label="请选择分摊参数"
          />

          <ProFormDigit width={100} label="分摊比例" name="shareParamPopout" min={0} max={100} />

        </ModalForm>

        {/* 分摊更新 */}
        <UpdateFormDrawer
          onSubmit={async (value) => {
          
            const {id,selectedParam} = value;
            const index = hasSetParamsList.findIndex(item=>item.id == id);
            let temp = hasSetParamsList;
            temp[index] = value;
            if(selectedParam){
                //修改了分摊参数名
                const {shareParamCode,shareParamName} = selectedParam;
                temp[index] = {...temp[index],shareParamCode,shareParamName}
                // console.log({shareParamCode,shareParamName,'temp[index]':temp[index]});
            }
            setHasSetParamsList([].concat(temp));
            setDrawerUpdateModalVisible(false);
            if (actionDrawertableRef.current) {
             actionDrawertableRef.current.reload();
           }
              
          }}
          onCancel={() => {
            drawerUpdateModalVisible(false);
            setCurrentRow(undefined);
          }}
          currentResponsibilityRow={currentResponsibilityRow}
          drawerUpdateModalVisible={drawerUpdateModalVisible}
          drawerUpdateModalVisibleChange={drawerUpdateModalVisibleChange}
          values={currentRow || {}}


        />
      </DrawerForm>


      {/* 选择复制抽屉 */}
      {
        drawerType != 0 && (
          <DrawerContent
            columns={drawerType == 1 ? responsibilityColumns : accountSubjectColumns}
            visible={copySelectDrawerVisible}
            currentRow={currentRow}
            title={drawerType == 1 ? '选择复制目标' : '选择会计科目'}
            defaultSelected={drawerType == 1?[]:selectedAccountSubjects}
            pageContainerConfig={(tableRef) => {

              return {
                header: {
                  title: ''
                }
              }
            }}
            onVisibleChange={(bool) => setCopySelectDrawerVisible(bool)}
            renderListFunc={drawerType == 1 ? getCopyableTableList : getAccountingSubjects}
            config={{ rowKeys: 'id', tableSearch: false }}
            tableSearch={false}
            expandable={{
              expandedRowKeys:expandedRowKeys
            }}
            onFinishFunc={async (value, selectedRowKeys, selectedRows) => {
              // console.log({ value, selectedRowKeys, selectedRows,drawerType });
              if (drawerType == 1) {
                const { id } = currentRow;
                const resp = await copyParamsList({ id, responsibilityIds: selectedRowKeys });
                const { status } = resp;
                if (status == 200) {
                  setCurrentRow(undefined);
                  setCopySelectDrawerVisible(false);
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }

              if (drawerType == 2) {
                
                //selectedRows为空标识没有编辑
                let selectedItemNames = selectedRows.map(item => item.accountingName);

                if(edit){
                  if(selectedRows.length>0){
                    if (updateFormRef.current) {
                      updateFormRef.current.setFieldsValue({ accountingNames: selectedItemNames.join(','), accountingIds: selectedRowKeys.join(',') })
                    }
                  }
                }
                if(!edit){
                  
                    if (ref.current) {
                      ref.current.setFieldsValue({ accountingName:selectedItemNames.join(','), accountingIds: selectedRowKeys.join(',') })
                    }
                
                }
                setCopySelectDrawerVisible(false);
              }


              setDrawerType(0);
            }}
          />
        )
      }




      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          // console.log({ '编辑': value });
          // // return;
          // console.log(updateFormRef.current.getFieldsValue(true));
          const { accountingIds } = updateFormRef.current.getFieldsValue(true);
          const { responsibilityId,responsibilityName,responsibilityCode,shareLevel,ifDisable, costNode,alias, id,isShareCost=1 } = value;
          console.log({alias});

          const success = await editCostshareparamConnectList(ifDisable ? {
            responsibilityId, costNode, id,responsibilityName,responsibilityCode,shareLevel,isShareCost,alias
          } : { responsibilityId,accountingIds, costNode,alias,id,responsibilityName,responsibilityCode,shareLevel,isShareCost });

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

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

      />
    </PageContainer>
  );
};

export default CostAllocationParamsConnect;
