import React, { useEffect, useState } from 'react';
import { Modal, Table, Checkbox, message, Spin, Button } from 'antd';
import { getDevidedData, getJuryData, saveDevidedData } from './service';

interface ReviewDivisionProps {
  modalVisible: boolean;
  onCancel: () => void;
  title: any;
  values: any;
}

/**
 * 保存评审分工
 * @param fields
 */

export const handleSave = async (fields: any) => {
  try {
    await saveDevidedData(fields);
    message.success('保存成功');
    return true;
  } catch (error) {
    message.error('保存失败');
    return false;
  }
};

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

const ReviewDevided: React.FC<ReviewDivisionProps> = (props) => {
  const { modalVisible, onCancel, title, values } = props;
  //存储评委数据
  const [juryData, setJuryData] = useState<any[]>([]);
  //存储表数据
  const [totalTableData, setTotalTableData] = useState<any[]>([]);
  //存储表头
  const [totalTableColumns, setTotalTableColumns] = useState<any[]>([]);
  //表格loading
  const [tableLoading, setTableLoadings] = useState<boolean>(false);
  //modal loading
  const [modalLoading, setModalLoading] = useState<boolean>(false);
  //评审分工查看状态
  const [viewStatus, setViewStatus] = useState<boolean>(false);
  //全部参数
  // const juryParams = '1331563852445253632';
  const juryParams = values == undefined ? '' : values.id;
  useEffect(() => {
    setTableLoadings(true);
    const status = values == undefined ? false : (values.status == 1 || values.status == 0 ? false : true)
    console.log(status)
    setViewStatus(status)
    if (juryParams == '') {
    } else {
      //获取评委
      getJuryData(juryParams).then((res) => {
        if (res.code == 200) {
          setJuryData(res.data);
          //获取分工数据
          if (juryParams == null) {
          } else {
            getDevidedData(juryParams).then((response) => {
              if (response.code == 200) {
                //调用数据处理方法并初始化表格
                InitializeTable(res.data, response.data);
                setTableLoadings(false);
              }
            });
          }
        }
      });
    }
  }, [modalVisible, values]);

  //初始化表格方法
  const InitializeTable = (columns: any, data: any) => {
    //处理数据
    let totalData: any[] = [];
    let count = 0;
    data.forEach((ele: any) => {
      if (ele.hasOwnProperty('subCategoryList')) {
        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: false,
                actType: inner.category,
                rvwType: ele.rvwType,
                juryMemberId: e.id,
                roomId: juryParams,
              };
            });
            inner.divideMap = obj;
          } else {
            let obj = { ...inner.divideMap };
            columns.forEach((e: any) => {
              if (obj.hasOwnProperty(e.id)) {
                obj[e.id].checked = true;
              } else {
                obj[e.id] = {
                  checked: false,
                  actType: inner.category,
                  rvwType: ele.rvwType,
                  juryMemberId: e.id,
                  roomId: juryParams,
                };
              }
            });
            inner.divideMap = obj;
          }
          Object.assign(inner, inner.divideMap);
          totalData.push(inner);
        });
      }
    });

    //处理表头
    const tcolumns: any[] = [
      {
        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={values == undefined ? false : (values.status == 1 || values.status == 0 ? 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 {
                data[jury][value.juryMemberId].checked = event.target.checked;
              }

              setTotalTableData(data);
            }}
            defaultChecked={value.checked}
            checked={value.checked}
          />
        ),
      });
    });
    console.log(totalData);
    setTotalTableColumns(tcolumns);
    setTotalTableData(totalData);
  };

  const onSubmit = async () => {
    setModalLoading(true);
    console.log(totalTableData);
    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('存在评审项未分配评委，请重新勾选');
      setModalLoading(false);
      return;
    }
    if(a == totalTableData.length - 1) {} else {
      if (e == 0) {
        message.info('请允许报价评审专家查看报价');
        setModalLoading(false);
        return;
      }
    }
    const success = await handleSave({ divideList: data });
    if (success) {
      setModalLoading(false);
      setTotalTableData([])
      onCancel();
    }
  };

  const onSelect = (record: any, selected: any) => {
    setTableLoadings(true);
    let select = totalTableData;
    select.forEach((ele: any) => {
      if (ele.key == record.key) {
        juryData.forEach((element) => {
          ele[element.id].checked = selected;
        });
      }
    });
    setTotalTableData(select);
  };

  return (
    <>
      <Spin spinning={modalLoading} delay={300}>
        <Modal
          destroyOnClose
          title={title}
          visible={modalVisible}
          onCancel={() => {
            onCancel()
            setTotalTableData([])
          }}
          width={800}
          footer={viewStatus ? false : [
            <Button key="back" onClick={() => {
              onCancel()
              setTotalTableData([])
            }}>
              取消
            </Button>,
            <Button key="submit" type="primary" loading={modalLoading} onClick={() => onSubmit()}>
              保存
            </Button>,
          ]}
        >
          <Table
            bordered
            pagination={false}
            columns={totalTableColumns}
            dataSource={totalTableData}
            size="middle"
            key="1"
            rowKey="key"
            loading={tableLoading}
            rowSelection={{
              hideSelectAll: true,
              onSelect: (record: any, selected: any) => {
                onSelect(record, selected);
                setTableLoadings(false);
              },
              getCheckboxProps: (record) => ({
                disabled: viewStatus == true ? true : record.rvwName == '详审' && record.category == 0,
              }),
            }}
          />
        </Modal>
      </Spin>
    </>
  );
};

export default ReviewDevided;
