import PageContent from '@/components/PageContent';
import { Button, Tabs, Space, Drawer, Timeline, message } from 'antd';
import styles from './index.less';
import { useEffect, useMemo, useRef, useState } from 'react';
import axios from 'axios';
import {
  useLocation,
  useParams,
  useRequest,
  useSearchParams,
  useNavigate,
} from '@umijs/max';
import {
  queryPsrExcel,
  queryPsrMonthDetail,
  queryPsrMonthLast,
  queryPsrMonthList,
  queryPsrWorkLoad,
  querySavePsrMonth,
} from '../../services/psr';
import SaveModal from './components/saveOtherModal';
import CompareModal from './components/compareModal';
import CompareCom from './components/compareCom';
import dayjs from 'dayjs';
import { exportExcel, getUUID } from '../../utils/exportExcl';
const PSRDetail = () => {
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  const { id: projectId } = params;
  const {
    state: { project_name, flow_id, node_id },
  } = location;

  const [excelData, setExcelData] = useState();
  const [historyOpen, setHistoryOpen] = useState();
  const [open, setOpen] = useState(false);
  const [key, setKey] = useState();
  const [compareOpen, setCompareOpen] = useState(false);
  const [compareValues, setCompareValues] = useState([]);
  const [isOriginVer, setIsOriginVer] = useState(false); //是否原始版本 是的话只能另存不能编辑

  const luckysheetRef = useRef();
  const iframeRef = useRef();

  const unableEdit = (option) => {
    option.showtoolbar = false;
    option.enableAddRow = false;
    option.sheetFormulaBar = false;
    option.enableAddBackTop = false;
    option.showsheetbarConfig = {
      add: false,
      sheet: false,
    };
    option.cellRightClickConfig = {
      copy: false, // 复制
      copyAs: false, // 复制为
      paste: false, // 粘贴
      insertRow: false, // 插入行
      insertColumn: false, // 插入列
      deleteRow: false, // 删除选中行
      deleteColumn: false, // 删除选中列
      deleteCell: false, // 删除单元格
      hideRow: false, // 隐藏选中行和显示选中行
      hideColumn: false, // 隐藏选中列和显示选中列
      rowHeight: false, // 行高
      columnWidth: false, // 列宽
      clear: false, // 清除内容
      matrix: false, // 矩阵操作选区
      sort: false, // 排序选区
      filter: false, // 筛选选区
      chart: false, // 图表生成
      image: false, // 插入图片
      link: false, // 插入链接
      data: false, // 数据验证
      cellFormat: false, // 设置单元格格式
    };
  };

  //请求投标版、签字版psr excel
  const { run: runExcel } = useRequest(queryPsrExcel, {
    manual: true,
    formatResult: (res) => {
      if (res) {
        const jsonData = JSON.parse(res);
        renderSheet(jsonData);
      }
    },
  });

  //请求月度psr和现金流列表 data_type 1 psr 2 现金流
  const {
    data,
    run: runList,
    loading: listLoading,
  } = useRequest(
    (data) =>
      queryPsrMonthList({
        project_id: projectId,
        data_type: data_type,
        ...data,
      }),
    { manual: true },
  );

  //保存/另存为月度psr和现金流接口
  const { run: runSave, loading: saveLoading } = useRequest(
    (data) => querySavePsrMonth(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('保存成功');
        if (open) setOpen(false);
      },
      onError: () => {
        message.success('添加失败');
      },
    },
  );

  //请求月度psr和现金流详情接口
  const { run: runDetail } = useRequest((data) => queryPsrMonthDetail(data), {
    manual: true,
    formatResult: (res) => {
      if (res?.data) {
        let data = res.data;
        console.log(data);
        const day = dayjs(data.day).format('YYYY-MM');
        setExcelData({ ...data, dayFormat: day });
        setHistoryOpen(false);
        const jsonData = JSON.parse(data.json_data);
        renderSheet(jsonData, data.is_edit);
      }
    },
  });

  const data_type = useMemo(() => {
    if (key == '3') return 1;
    if (key == '4') return 2;
    return null;
  }, [key]);

  useEffect(() => {
    setCompareValues([]);
    if (key) {
      onChange(key);
    } else {
      runExcel({ gridKey: node_id });
    }
  }, [key]);

  const onChange = (key) => {
    if (key == '1') {
      runExcel({ gridKey: node_id });
    } else if (key == '2') {
      runExcel({ gridKey: flow_id });
    } else {
      initPsrActrual(key);
    }
  };

  const initPsrActrual = async (key) => {
    const data_type = key == '3' ? 1 : 2;
    // runList({ data_type });
    const res = await queryPsrMonthLast({ project_id: projectId, data_type });
    if (res.data?.length > 0 && res.data[0].json_data) {
      const day = dayjs(res.data[0].day).format('YYYY-MM');
      const isOrigin = day.includes('1970-01') ? 1 : 0;
      setIsOriginVer(isOrigin);
      setExcelData({ ...res.data[0], dayFormat: day });
      const data = JSON.parse(res.data[0].json_data);
      console.log(data);
      if (data.cell_data) data.celldata = JSON.parse(data.cell_data);
      if (data.config) data.config = JSON.parse(data.config);
      renderSheet(
        Array.isArray(data) ? data : [data],
        isOrigin ? 0 : res.data[0].is_edit,
      );
    }
  };

  const handlerSaveOther = (date) => {
    const luckyData = luckysheetRef.current?.toJson();
    if (luckyData?.data) {
      const params = {
        day: date,
        project_id: Number(projectId),
        json_data: JSON.stringify(luckyData.data),
        data_type: data_type,
      };
      runSave(params);
    }
  };
  const handlerSave = () => {
    const luckyData = luckysheetRef.current?.toJson();
    const params = {
      id: excelData?.id,
      data_type: excelData?.data_type,
      project_id: excelData?.project_id,
      day: dayjs(excelData?.day).format('YYYY-MM-DD'),
      json_data: JSON.stringify(luckyData.data),
    };
    runSave(params);
  };

  const exportExcl = (title) => {
    const luckyData = luckysheetRef.current?.toJson();
    exportExcel(luckyData.data, title);
  };

  const handlerLoad = () => {
    const contentWindow = iframeRef.current.contentWindow;
    luckysheetRef.current = contentWindow.luckysheet;
  };
  const renderSheet = (currentData, is_edit = false) => {
    console.log('==================', luckysheetRef.current);
    if (!luckysheetRef.current) {
      setTimeout(() => {
        renderSheet(currentData, is_edit);
      }, 500);
      return;
    }
    const data = currentData;
    //设置单元格不可编辑
    data?.forEach((item) => {
      item.config.authority = is_edit
        ? null
        : {
            sheet: true,
            hintText: '当前excel不可编辑！',
          };
    });
    let option = {
      lang: 'zh',
      showinfobar: false,
      showstatisticBar: false,
      data: JSON.parse(JSON.stringify(data)),
      hook: {
        cellMousedown: (cell, position, sheet) => {
          console.log(cell, sheet);
        },
        cellUpdated: () => {
          luckysheetRef.current.refreshFormula();
        },
        workbookCreateAfter: async () => {
          //当前为为终版psr标签并且可编辑状态时填充人日数据
          if (key == '3' && is_edit) {
            const res = await queryPsrWorkLoad({ project_id: projectId });
            if (res.data) {
              luckysheetRef.current.setCellValue(8, 4, res.data.Total);
              luckysheetRef.current.setCellValue(8, 8, res.data.Month);
            }
          }
        },
      },
    };
    option.data.forEach((item) => {
      delete item.data;
      delete item.cell_data;
      if (item.celldata) {
        item.celldata.forEach((cell) => {
          // 生成uuid
          if (!cell.v.cid) cell.v.cid = getUUID();
        });
      }
      // 默认禁止编辑
      // item.config.authority = { sheet: true, hintText };
    });

    console.log(option.data);
    //设置不可编辑
    if (!is_edit) unableEdit(option);

    luckysheetRef.current.destroy();
    luckysheetRef.current.create(option);
  };
  const renderTitle = (data_type, title) => {
    if (compareValues?.length == 2) {
      return (
        <div className={styles.exportDiv}>
          <Button
            type="primary"
            onClick={() => {
              setCompareValues([]);
              setTimeout(() => {
                initPsrActrual(key);
              }, 500);
            }}
          >
            退出比对
          </Button>
        </div>
      );
    }
    if (data_type == 0)
      return (
        <div className={styles.exportDiv}>
          <Button type="primary" onClick={() => exportExcl(title)}>
            导出
          </Button>
        </div>
      );
    return (
      <div className={styles.excelTitle}>
        <div>
          当前PSR表单：
          <span style={{ color: 'blue' }}>{excelData?.dayFormat}</span>
        </div>
        <Space>
          <Button
            type="primary"
            onClick={() => {
              runList();
              setHistoryOpen(true);
            }}
          >
            {`${title}历史版本`}
          </Button>
          <Button
            type="primary"
            onClick={() => setOpen(true)}
            disabled={!excelData?.is_edit}
          >
            另存为
          </Button>
          <Button
            type="primary"
            onClick={handlerSave}
            disabled={!excelData?.is_edit || isOriginVer}
          >
            保存
          </Button>
          <Button type="primary" onClick={() => setCompareOpen(true)}>
            比对
          </Button>
          <Button type="primary" onClick={() => exportExcl(title)}>
            导出
          </Button>
        </Space>
      </div>
    );
  };

  const items = [
    {
      key: '1',
      label: '投标版PSR',
      children: renderTitle(0, '投标版PSR'),
    },
    {
      key: '2',
      label: '签字版PSR',
      children: renderTitle(0, '签字版PSR'),
    },
    {
      key: '3',
      label: '终版PSR',
      children: renderTitle(1, '终版PSR'),
    },
    {
      key: '4',
      label: '现金流',
      children: renderTitle(2, '现金流'),
    },
  ];
  return (
    <PageContent>
      <div className={styles.titleDev}>
        <Button type="primary" onClick={() => navigate(-1)}>
          返回
        </Button>
        <span className={styles.title}>{project_name}</span>
      </div>
      <Tabs defaultActiveKey="1" type="card" items={items} onChange={setKey} />
      {compareValues?.length == 2 ? (
        <CompareCom values={compareValues} />
      ) : (
        <iframe
          style={{
            width: '100%',
            height: '80vh',
          }}
          ref={iframeRef}
          onLoad={handlerLoad}
          src="/luckysheet.html"
        />
      )}

      <Drawer
        title="历史版本"
        placement="right"
        loading={listLoading}
        onClose={() => setHistoryOpen(false)}
        open={historyOpen}
      >
        <Timeline
          items={data?.list?.map((item) => {
            return {
              children: (
                <a onClick={() => runDetail({ id: item.id })}>
                  {dayjs(item.day).format('YYYY-MM')}
                </a>
              ),
            };
          })}
        />
      </Drawer>
      <SaveModal
        loading={saveLoading}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={handlerSaveOther}
      />
      <CompareModal
        list={data?.list}
        open={compareOpen}
        onOk={(values) => {
          setCompareValues(values);
          setCompareOpen(false);
        }}
        onCancel={() => setCompareOpen(false)}
      />
    </PageContent>
  );
};
export default PSRDetail;
