/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-15 15:28:19
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';

import { createFromIconfontCN } from '@ant-design/icons';

import {
  ActionType,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect,
  ProFormDigit,
} from '@ant-design/pro-components';
import { ModalForm, ProFormCascader } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { message, Popconfirm, Modal } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import {
  addData,
  delData,
  editData,
  getIncomeCollectionList,
  incomeCollectionListConnectAccountingSubject,
} from './service';

import './style.less';
import { getResponsibilityCenterList } from '../../responsibilityCenterSet/responsibilityCenter/service';
import TableTransfer from './transform';
import React from 'react';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

const transferTableColumn = [
  {
    title: '会计科目编码',
    dataIndex: 'accountingCode',
    ellipsis: true,
  },
  {
    title: '会计科目名',
    dataIndex: 'accountingName',
    ellipsis: true,
  },
];

export default function AccountingSubMana() {
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);

  const columns: ProColumns[] = [
    {
      title: '收入归集Id',
      dataIndex: 'id',
    },
    {
      title: '开单科室状态',
      dataIndex: 'openDepartmentStatus',
      renderText(num) {
        return num == 1 ? '收益中心' : '成本中心';
      },
    },
    {
      title: '开单科室分配比例',
      align: 'right',
      dataIndex: 'openDepartmentProportion',
    },
    {
      title: '执行科室',
      dataIndex: 'startDepartmentStatus',
      renderText(num) {
        return num == 1 ? '收益中心' : '成本中心';
      },
    },
    {
      title: '执行科室比例',
      align: 'right',
      dataIndex: 'startDepartmentProportion',
    },
    {
      title: '归集到其他责任中心',
      dataIndex: 'responsibilityName',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'option',
      width: 200,
      valueType: 'option',
      render: (_: any, record: any) => {
        const { accountStatus } = record;
        return accountStatus == 0
          ? [
              <UpDataActBtn key={'edit'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
            ]
          : [
              <UpDataActBtn key={'act'} record={record} type="EDIT" />,
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>,
              <a
                key="ather"
                onClick={() => {
                  oprnTableTransform(record);
                }}
              >
                排除会计科目
              </a>,
            ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getIncomeCollectionList(params);
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    return [];
  };

  const delTableData = async (record: any) => {
    const resp = await delData([record.id]);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
      // message.success('操作成功!');
    }
  };

  const oprnTableTransform = (record: any) => {
    const ref = React.createRef<{ save: any }>();

    Modal.confirm({
      title: `排除会计科目`,
      icon: <></>,
      width: 750,
      centered: true,
      okText: '确定',
      cancelText: '取消',
      content: (
        <TableTransfer
          ref={ref}
          keyName="accountingCode"
          record={record}
          onSave={(keys, rows) => onSaveHandle(keys, rows, record)}
          leftColumns={transferTableColumn}
          rightColumns={transferTableColumn}
          dataSource={[]}
        ></TableTransfer>
      ),
      onOk: () => {
        return ref.current && ref.current.save();
      },
    });
  };

  const onSaveHandle = async (keys: Key[], rows: any[], record: any) => {
    const { id } = record;
    const resp = await incomeCollectionListConnectAccountingSubject({
      id,
      accountCodes: keys,
    });
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const { openDepartmentProportion, startDepartmentProportion } = formVal;
    const result = {
      ...formVal,
      responsibilityCodes: formVal.responsibilityCodes
        ? formVal.responsibilityCodes.join('/')
        : null,
      startDepartmentProportion: startDepartmentProportion
        ? startDepartmentProportion
        : 0,
      openDepartmentProportion: openDepartmentProportion
        ? openDepartmentProportion
        : 0,
    };

    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const resp = await editData(result);
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}收入归集设置`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                responsibilityCodes: record.responsibilityCodes
                  ? record.responsibilityCodes.split('/')
                  : [],
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormSelect
          name="openDepartmentStatus"
          label="开单科室状态"
          options={[
            { label: '收益中心', value: 1 },
            { label: '成本中心', value: 2 },
          ]}
          placeholder="请选择状态"
          rules={[{ required: true, message: '请选择开单科室状态!' }]}
        />
        <ProFormDependency name={['openDepartmentStatus']}>
          {({ openDepartmentStatus }) => {
            return openDepartmentStatus == 2 ? (
              <ProFormDigit
                disabled
                label="开单科室比例"
                initialValue={0}
                rules={[
                  {
                    required: false,
                    message: '开单科室比例是必填项！',
                  },
                ]}
                name="openDepartmentProportion"
              />
            ) : (
              <ProFormDigit
                label="开单科室比例"
                rules={[
                  {
                    required: true,
                    message: '开单科室比例是必填项！',
                  },
                ]}
                name="openDepartmentProportion"
              />
            );
          }}
        </ProFormDependency>
        <ProFormSelect
          name="startDepartmentStatus"
          label="执行科室状态"
          options={[
            { label: '收益中心', value: 1 },
            { label: '成本中心', value: 2 },
          ]}
          placeholder="请选择状态"
          rules={[{ required: true, message: '请选择执行科室状态!' }]}
        />
        <ProFormDependency name={['startDepartmentStatus']}>
          {({ startDepartmentStatus }) => {
            return startDepartmentStatus == 2 ? (
              <ProFormDigit
                disabled
                label="执行科室比例"
                initialValue={0}
                rules={[
                  {
                    required: false,
                    message: '执行科室比例是必填项！',
                  },
                ]}
                name="startDepartmentProportion"
              />
            ) : (
              <ProFormDigit
                label="执行科室比例"
                rules={[
                  {
                    required: true,
                    message: '执行科室比例是必填项！',
                  },
                ]}
                name="startDepartmentProportion"
              />
            );
          }}
        </ProFormDependency>
        <ProFormDependency
          name={['openDepartmentStatus', 'startDepartmentStatus']}
        >
          {({ openDepartmentStatus, startDepartmentStatus }) => {
            return openDepartmentStatus == 2 && startDepartmentStatus == 2 ? (
              <ProFormCascader
                placeholder={'请选择'}
                label="选择责任中心："
                name="responsibilityCodes"
                fieldProps={{
                  fieldNames: {
                    label: 'responsibilityName',
                    value: 'responsibilityCode',
                    children: 'child',
                  },
                  onChange: (val: any) => {},
                }}
                request={async () => {
                  const resp = await getResponsibilityCenterList({
                    pageSize: 50,
                    current: 1,
                  });
                  if (resp) {
                    return resp.list;
                  }
                }}
              />
            ) : (
              <></>
            );
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  useEffect(() => {}, []);

  return (
    <KCIMPagecontainer className="AccountingSubMana" title={false}>
      <div
        className="toolBar"
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <div className="title">收入归集设置</div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

      <div>
        <KCIMTable
          scroll={{ y: `calc(100vh - 234px)` }}
          columns={columns as ProColumns[]}
          actionRef={tableRef}
          rowKey="id"
          request={(params) => getTableData(params)}
        />
      </div>
    </KCIMPagecontainer>
  );
}
