/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-07-30 19:55:25
 * @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, Cascader,Modal } 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, DrawerForm, ProFormSelect, ProFormTextArea, ProFormDigit } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import UpdateFormDrawer from './updateForm_drawer';
// import CAUpload from '@/components/CAUpload';
import {
  getCostshareparamConnectList, editCostshareparamConnectList, delCostshareparamConnect,
  addCostshareparamConnect, getResponsibilityCenterSelecterList, getAccountingSubjectForSelecter,
  getHasSetParamsList, getParamsSelectableList, saveParamsList
} from './service';
import { set } from 'lodash-es';

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

    {
      title: '分摊级别',
      dataIndex: 'shareLevel',
      key: 'shareLevel',
      hideInSearch: true,
    },
    {
      title: '责任中心编码',
      dataIndex: 'responsibilityCode',
      key: 'responsibilityCode',
      hideInSearch: true,
    },
    {
      title: '责任中心名',
      dataIndex: 'responsibilityName',
      key: 'responsibilityName',
      hideInSearch: false,
    },
    {
      title: '成本项目名称',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: true,
    },
    {
      title: '成本项目编码',
      dataIndex: 'accountingCode',
      key: 'accountingCode',
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'costNode',
      key: 'costNode',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config1"
          onClick={() => {
            setDrawerVisible(true);
            setCurrentRow(record);
            setCurrentResponsibilityRow(record);
          }}
        >
          分摊参数设置
        </a>,
        <a
          key="config2"
          onClick={() => {
            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,
    },
    {
      title: '分摊参数名称',
      dataIndex: 'shareParamName',
      key: 'shareParamName',
      hideInSearch: false,
    },
    {
      title: '分摊比例',
      dataIndex: 'shareParamPopout',
      key: 'shareParamPopout',
      hideInSearch: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      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 [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [cascaderOptions, setCascaderOptions] = useState([]);
  const actionRef = useRef(); //表格
  const ref = useRef();   //新增表单
  const [currentResponsibilityRow, setCurrentResponsibilityRow] = useState({});
  const [selectedCascader, setSelectedCascader] = useState(null);
  const [currentRow, setCurrentRow] = useState({});
  const [ifDisable, setIfDisable] = useState(false);
  const [selectedResponsibilityId, setSelectedResponsibilityId] = useState(null);


  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);


  /**
   *
   * @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();
      }
    }
  };

  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();
      }
  }

  //级联回调
  const cascaderChangeHandle = (value) => {
    setSelectedCascader(value[value.length - 1]);
  }
  //分摊参数回调
  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);
  }

  const handleDrawerModalVisible = (bool) => {
    setDrawerMadalVisible(bool);
  }


  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={() => {
              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) {
            ref.current.resetFields();
          }
          handleModalVisible(bool);
        }}
        onFinish={async (value) => {
          const { costNode } = value;
          const success = await addCostshareparamConnect({
            responsibilityId: selectedResponsibilityId,
            accountingId: selectedCascader > 0 ? selectedCascader : 0,
            costNode

          });
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.accountingType" defaultMessage="请选择责任中心" />
              ),
            },
          ]}
          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);
                if (selected && selected[0].calcType == 0) {
                  setIfDisable(true);
                } else {
                  setIfDisable(false);
                }
              }
            },
          }}
          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="请选择责任中心"
        />
        <ProForm.Group style={{ marginBottom: 20 }}>
          <div style={{ marginLeft: 115 }}>请选择成本科目:</div>
          <Cascader disabled={ifDisable} options={cascaderOptions} onChange={cascaderChangeHandle} placeholder="请选择成本科目" />
        </ProForm.Group>

        <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}
          // request={[]}
          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={{
            pageSize: 10,
          }}
          search={false}
        />
        <ModalForm
          title="新增分摊参数"
          width="800px"
          labelCol={{ span: 5, offset: 3 }}
          layout={'horizontal'}
          visible={drawerMadalVisible}
          formRef={drawerModalRef}
          onVisibleChange={(bool) => {
            if (ref.current) {
              ref.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: (
                  <FormattedMessage id="pages.searchTable.accountingType" defaultMessage="请选择责任中心" />
                ),
              },
            ]}

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

            request={async () => {
              const { id } = currentResponsibilityRow;
              const resp = await getParamsSelectableList({ id });
              const { data, status } = resp;
              console.log({ resp });
              if (status == 200) {
                const temp = data.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} = value;
               const index = hasSetParamsList.findIndex(item=>item.id == id);
               const temp = hasSetParamsList;
               temp[index] = value;
               console.log({value,temp});
               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>



      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          console.log({ '编辑': value });
          const { responsibilityId, ifDisable, accountingId, costNode, id } = value;

          const success = await editCostshareparamConnectList(ifDisable ? {
            responsibilityId, costNode, id
          } : { responsibilityId, accountingId, costNode, id });

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

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

      />
    </PageContainer>
  );
};

export default DepartmentMana;
