/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-02 02:09:05
 * @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, message, Space, Drawer,Table } 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 { ModalForm, ProFormText, ProFormSelect,DrawerForm,ProFormDigit} from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import UpdateFormDrawer from './updateForm_drawer';
// import CAUpload from '@/components/CAUpload';
import { getCostshareparamList, editCostshareparamList, delCostshareparam, addCostshareparam,updateCostShareParamByAccountId } from './service';
import { getAccountingSubjectList} from '../accountingSubject/service';

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

    {
      title: '成本分摊参数名',
      dataIndex: 'shareParamName',
      key: 'shareParamName',
      hideInSearch: false,
    },
    {
      title: '成本分摊参数编号',
      dataIndex: 'shareParamCode',
      key: 'shareParamCode',
      hideInSearch: true,
    },
    {
      title: '计算方式',
      dataIndex: 'calcType',
      key: 'calcType',
      hideInSearch: true,
      render: (text) => <>{text == 1 ? '手动填写' : '按对应会计科目计算'}</>,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) =>{
        const {calcType} = record;
        const groups = [
          <a
            key="config"
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            编辑
          </a>,
          <Popconfirm
            key="subscribeAlert"
            title="是否确定删除?"
            onConfirm={() => {
              setCurrentRow(record);
              delListHandler(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>,
        ]

        return calcType==1?groups:[...groups,<a
          key="config"
          onClick={() => {
            setDrawerVisible(true);
            setCurrentRow(record);
            setCurrentResponsibilityRow(record);
          }}
        >
          设置对应会计科目
        </a>,]
      } 
    },
  ];

  const drawerTableColumns = [
    {
      title: '成本科目编码',
      dataIndex: 'accountingCode',
      key: 'accountingCode',
      hideInSearch: true,
    },
    {
      title: '成本科目名称',
      dataIndex: 'accountingName',
      key: 'accountingName',
      hideInSearch: false,
    }
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef(); //表格
  const ref = useRef();   //新增表单
  const [currentRow, setCurrentRow] = useState({});
  const [currentResponsibilityRow, setCurrentResponsibilityRow] = useState({});
  
  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 [accountType, setAccountType] = useState(1);
  const [selectedRowKeys,setSelectedRowKeys] = 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 getCostshareparamList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

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


    //分摊参数回调
    const drawerVisibleChange = async (bool) => {
      // console.log({currentRow});
      if (bool) {
          if(actionDrawertableRef.current){
            actionDrawertableRef.current.reload();
          }
      }
      setDrawerVisible(bool);
    }
  
    const handleDrawerModalVisible = (bool) => {
      setDrawerMadalVisible(bool);
    }

    const onTabChange = (key)=>{
      setAccountType(Number(key));
      if (actionDrawertableRef.current) {
        actionDrawertableRef.current.reload();
      }
    }

  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 success = await addCostshareparam(value);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="成本分摊参数名"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.shareParamName" defaultMessage="成本分摊参数名是必填项" />
              ),
            },
          ]}
          width="sm"
          name="shareParamName"
        />
        <ProFormText
          label="成本分摊参数编号"
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.shareParamCode" defaultMessage="成本分摊参数编号是必填项" />
              ),
            },
          ]}
          width="sm"
          name="shareParamCode"
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.accountingType" defaultMessage="请选择计算方式" />
              ),
            },
          ]}
          options={[
            {
              value: 1,
              label: '手动填写',
            },
            {
              value: 2,
              label: '按对应会计科目计算',
            },
          ]}
          width="sm"
          name="calcType"
          label="计算方式"
        />
      </ModalForm>


      {/* 设置对应会计科目 */}
      <DrawerForm
        title="设置对应会计科目"
        formRef={drawerFormRef}
        visible={drawerVisible}
        onVisibleChange={(visible) => drawerVisibleChange(visible)}
        // onFinish={(value) => onSubmit({ ...values, ...value })}
        onFinish={async () => {

          const {id} = currentResponsibilityRow;
          console.log({selectedRowKeys,currentResponsibilityRow});
          const resp = await updateCostShareParamByAccountId({costShareParamId:id,accountIds:selectedRowKeys});
          const {status} = resp;
          setDrawerVisible(false);
          if(status==200){
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          
        }}
      >
        <PageContainer
             header={{
               title:''
             }}
             tabList={[
              {
                tab: '收益',
                key: 1,
              },
              {
                tab: '支出',
                key: 2,
              },
            ]} 
            onTabChange={onTabChange}  
        >
        <ProTable
          columns={drawerTableColumns}
          // request={[]}
          rowKey="id"
          actionRef={actionDrawertableRef}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            selectedRowKeys:selectedRowKeys,
            onChange:(selectedRowKeys, selectedRows)=>{
              setSelectedRowKeys(selectedRowKeys);
            }
          }}
          tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) =>{
            setSelectedRowKeys(selectedRowKeys);
              return (
                <Space size={24}>
                  <span>
                    已选 {selectedRowKeys.length} 项
                    <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                      取消选择
                    </a>
                  </span>
                </Space>
              )
          }}
          request={async (params = {}, sort, filter) => {
            const {id} = currentResponsibilityRow;
            const result = await getAccountingSubjectList({accountType,shareParamId:id});
            const {status,data} = result;
            if(status==200){
              const selectedList = data.list.filter(item=>item.isSelect);
              const temp = selectedList.map(item=>item.id);
              setSelectedRowKeys(temp);
              return {
                data: data.list,
                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 || {}}
       

        />
        </PageContainer>
        
      </DrawerForm>


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

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