import React, { useEffect, useState } from 'react';
import { Modal, Table, Checkbox, message, Button, Empty } from 'antd';
import { getDevidedData, getJuryData, saveDevidedData } from './service';
import { getProMethod, getRoomTypeByEva } from '@/utils/session';
import { getURLInformation } from '@/utils/CommonUtils';
import { btnAuthority } from '@/utils/authority';

interface ReviewDivisionProps {
  modalVisible: boolean;
  onCancel: () => void;
  title: any;
  roomId?: string;
  status?: number;
}

/**
 * 评审分工
 * @param props
 */

const ReviewDevided: React.FC<ReviewDivisionProps> = (props) => {
  const { modalVisible, onCancel, title, roomId, status } = props;
  //存储评委数据
  const [juryData, setJuryData] = useState<any[]>([]);
  //存储表数据
  const [totalTableData, setTotalTableData] = useState<any[]>([]);
  //存储表头
  const [totalTableColumns, setTotalTableColumns] = useState<any[]>([]);
  //表格loading
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  //评审分工查看状态
  const [viewStatus, setViewStatus] = useState<boolean>(false);
  //评审分工空状态
  const [emptyStatus, setEmptyStatus] = useState<boolean>(false);
  //全部参数
  // const juryParams = '1331563852445253632';
  const juryParams = roomId == undefined ? '' : roomId;
  //获取资审方式
  // const roomType = getURLInformation('roomType') == null ? '2' : getURLInformation('roomType');
  const roomType = getRoomTypeByEva();//评审分工挪入评审室，需要取session中的资审方式
  //获取采购方式
  const MethodDict = getProMethod();
  useEffect(() => {
    if (modalVisible) {
      setTableLoading(true);
      const btnStatus =
        status == undefined ? false : status != 1 ? false : true;
      setViewStatus(btnStatus);
      if (juryParams == '') {
      } else {
        //获取评委
        getJuryData(juryParams).then((res) => {
          if (res?.code == 200) {
            let juryData = res?.data;
            if (juryData.length == 0) {
              setEmptyStatus(true);
            } else {
              setEmptyStatus(false);
              setJuryData(juryData);
              //获取分工数据
              if (juryParams == null) {
              } else {
                getDevidedData(juryParams).then((response) => {
                  if (response?.code == 200) {
                    //调用数据处理方法并初始化表格
                    InitializeTable(juryData, response?.data);
                  }
                });
              }
            }
          }
        }).finally(() => {
          setTableLoading(false);
        });
      }
    }
  }, [modalVisible, roomId]);

  //初始化表格方法
  const InitializeTable = (columns: any, data: any) => {
    //处理数据
    let totalData: any[] = [];
    let count = 0;
    data?.forEach((ele: any) => {
      ele.subCategoryList.forEach((element: any, index: any) => {
        let inner = element;
        count = count + 1;
        inner.key = count;
        inner.rvwName = ele.rvwName;
        inner.rowSpan = index == 0 ? ele.subCategoryList.length : 0;
        if (inner.divideMap == null) {
          let obj = {};
          columns.forEach((e: any) => {
            obj[e.id] = {
              checked: inner.category == 0 && ele.rvwType == 2 ? false : true,
              actType: inner.category,
              rvwType: ele.rvwType,
              juryMemberId: e.id,
              roomId: juryParams,
            };
          });
          inner.divideMap = obj;
          inner.allStatus = inner.category == 0 && ele.rvwType == 2 ? false : true;
        } else {
          let obj = { ...inner.divideMap };
          let count = 0;
          columns.forEach((e: any) => {
            if (obj.hasOwnProperty(e.id)) {
              obj[e.id].checked = true;
              count += 1;
            } else {
              obj[e.id] = {
                checked: false,
                actType: inner.category,
                rvwType: ele.rvwType,
                juryMemberId: e.id,
                roomId: juryParams,
              };
            }
          });
          inner.divideMap = obj;
          inner.allStatus = count == columns.length;
        }
        Object.assign(inner, inner.divideMap);
        totalData.push(inner);
      });
    });

    //处理表头
    const tcolumns: any[] = [
      {
        title: '',
        dataIndex: 'allStatus',
        key: 'allStatus',
        align: 'center',
        width: 60,
        render: (value: any, record: any, index: any) => {
          return (
            <Checkbox
              disabled={
                status != 1
                  ? record.rvwName == '详审' && record.category == 0
                  : true
              }
              onChange={(event) => {
                const data = [...totalData];
                const selected = event.target.checked;
                data.forEach((ele: any) => {
                  if (ele.key == record.key) {
                    ele.allStatus = selected;
                    columns.forEach((element: any) => {
                      ele[element.id].checked = selected;
                    });
                  }
                });
                setTotalTableData(data);
              }}
              checked={record.allStatus}
            />
          );
        },
      },
      {
        title: '',
        dataIndex: 'rvwName',
        key: 'rvwName',
        align: 'center',
        render: (value: any, record: any, index: any) => {
          if (!record.name) {
            return {
              children: value,
              props: {
                colSpan: 2,
                style: { textAlign: 'center' },
              },
            };
          }
          return {
            children: value,
            props: {
              rowSpan: record.rowSpan,
            },
          };
        },
      },
      {
        title: '评审项类别',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        render: (value: any, record: any, index: any) => {
          if (!record.name) {
            return {
              children: '',
              props: {
                colSpan: 0,
              },
            };
          }
          return value;
        },
      },
    ];
    columns.forEach((ele: any) => {
      tcolumns.push({
        title: ele.name,
        dataIndex: ele.id,
        key: ele.id,
        align: 'center',
        render: (value: any, record: any, index: any) => (
          <Checkbox
            disabled={status != 1 ? false : true}
            onChange={(event) => {
              const data = [...totalData];
              const jury = data.findIndex((item: any) => item.key == record.key);
              const isView = data.length - 1;

              if (
                data[jury][value.juryMemberId].rvwType == 2 &&
                data[jury][value.juryMemberId].actType == 0
              ) {
                columns.forEach((ele: any) => {
                  if (ele.id == value.juryMemberId) {
                    if (event.target.checked == true) {
                      data[jury][value.juryMemberId].checked = event.target.checked;
                      data[isView][value.juryMemberId].checked = event.target.checked;
                    } else {
                      data[jury][value.juryMemberId].checked = event.target.checked;
                    }
                  } else {
                    data[jury][ele.id].checked = false;
                  }
                });
              } else {
                let count = 0;
                data[jury][value.juryMemberId].checked = event.target.checked;
                columns.forEach((ele: any) => {
                  if (data[jury][ele.id].checked == true) {
                    count += 1;
                  }
                });
                data[jury].allStatus = count == columns.length;
              }
              setTotalTableData(data);
            }}
            checked={value.checked}
          />
        ),
      });
    });
    setTotalTableColumns(tcolumns);
    setTotalTableData(totalData);
  };

  //保存方法
  const onSubmit = async () => {
    setTableLoading(true);
    let data: any[] = [];
    let count = 0;
    let e = 0;
    let a = 0;
    let j = totalTableData.length - 1;

    totalTableData.forEach((element: any) => {
      let num = 0;
      let b = 0;
      juryData.forEach((ele: any) => {
        if (element[ele.id].rvwType == 1) {
          b = b + 1;
        }
        if (element[ele.id].checked == true) {
          data.push(element[ele.id]);
          if (
            element[ele.id].rvwType == 2 &&
            element[ele.id].actType == 0 &&
            totalTableData[j][ele.id].checked
          ) {
            e = e + 1;
          }
        } else if (element[ele.id].checked == false) {
          num = num + 1;
        }
      });
      if (num == juryData.length) {
        count = count + 1;
      }
      if (b == juryData.length) {
        a = a + 1;
      }
    });
    if (count > 0) {
      message.info('存在评审项未分配评委，请重新勾选');
      setTableLoading(false);
      return;
    }
    if (a == j) {
    } else {
      //预审 跳过报价和可查看报价
      //多轮招募 跳过报价和可查看报价
      if (roomType == '1' || MethodDict == 'procurement_mode_4') {
      } else {
        if (e == 0) {
          message.info('请允许报价评审专家查看报价');
          setTableLoading(false);
          return;
        }
      }
    }
    await saveDevidedData({ divideList: data }).then((res) => {
      if (res?.code == 200) {
        message.success('保存成功');
        setTotalTableData([]);
        onCancel();
      }
    }).finally(() => {
      setTableLoading(false);
    })
  };

  return (
    <>
      <Modal
        destroyOnClose
        title={title}
        visible={modalVisible}
        onCancel={() => {
          onCancel();
          setTotalTableData([]);
        }}
        width={1000}
        centered
        footer={[
          <Button
            key="back"
            onClick={() => {
              onCancel();
              setTotalTableData([]);
            }}
          >
            返回
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={tableLoading}
            onClick={() => onSubmit()}
            hidden={viewStatus || emptyStatus}
            disabled={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])}
          >
            保存
          </Button>
        ]}
      >
        {emptyStatus ? (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <Table
            bordered
            pagination={false}
            columns={totalTableColumns}
            dataSource={totalTableData}
            size="small"
            key="1"
            rowKey="key"
            loading={tableLoading}
          />
        )}
      </Modal>
    </>
  );
};

export default ReviewDevided;
