import React, {useRef, useState} from 'react';
import {PageContainer} from "@ant-design/pro-layout";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {Button, Card, message, Modal, Table} from "antd";
import {
  EditableProTable,
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormSelect,
  ProFormText
} from '@ant-design/pro-components';
import {addPaper360, deleteSource, deleteTarget, paper360List, sendEmail, targetAddUser} from "@/services/paperManager";
import {getPageQuery} from "@/utils/utils";
import {history} from "@@/core/history";
import Space from 'antd-mobile/es/components/space';
import {chooseFile} from "@/utils/fileUtils";
import * as XLSX from 'xlsx';


const Paper360List: React.FC = (props) => {
    const ref = useRef<ActionType>();
    const [showAddPaper360Dialog, setShowAddPaper360Dialog] = useState(false);
    const [isEdit, setIsEdit] = useState(false);
    const addPaper360FormRef = useRef<ProFormInstance>();
    const paperId = parseInt(getPageQuery().id + '');
    const [showTargetAddUserDialog, setShowTargetAddUserDialog] = useState(false);
    const targetAddUserFormRef = useRef<ProFormInstance>();
    const [showSendConfirmDialog, setShowSendConfirmDialog] = useState(false);
    const [showDeleteTargetDialog, setShowDeleteTargetDialog] = useState(false);
    const [showDeleteSourceDialog, setShowDeleteSourceDialog] = useState(false);

    const [currentSource, setCurrentSource] = useState<API.Paper360AnswerUser>();
    const [currentTarget, setCurrentTarget] = useState<API.Paper360>();
    const [confirmLoading, setConfirmLoading] = useState(false);


    if (!paperId) {
      return <>访问异常</>
    }

    const getRelation = (text: string) => {
      if (text == "下级") {
        return 1
      } else if (text == "平级") {
        return 2
      } else if (text == "上级") {
        return 3
      } else if (text == "自评") {
        return 4
      } else {
        return 0
      }
    }

    const getRelationType = (type: number) => {
      if (type == 1) {
        return "下级"
      } else if (type == 2) {
        return "平级"
      } else if (type == 3) {
        return "上级"
      } else if (type == 4) {
        return "自评"
      } else {
        return "未知"
      }
    }

    const importEvaluator = () => {
      chooseFile({accept: '.xls,.xlsx', fileTypes: ['xls', 'xlsx'], fileSize: 1}).then(file => {
        const reader = new FileReader();
        reader.onload = function (e) {
          var fileData = e.target.result;
          const workbook = XLSX.read(fileData, {type: 'binary'});
          for (const sheet in workbook.Sheets) {
            let answerUsers = []
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], {header: 1});
              for (let i = 0; i < data.length; i++) {
                answerUsers.push({id: i, account: data[i][0], name: data[i][1], relation: getRelation(data[i][2])})
              }
            }
            addPaper360FormRef.current?.setFieldsValue({
              answerUsers: answerUsers
            });
          }
        }
        reader.readAsBinaryString(file);
      })
    }

    const answerUserColumns: ProColumns<API.Paper360AnswerUser>[] = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '邮箱',
        dataIndex: 'account',
        key: 'account',
        ellipsis: true,
        width: 250
      },
      {
        title: '关系',
        dataIndex: 'relation',
        key: 'relation',
        render: (text, record, _, action) => {
          return <>{getRelationType(text)}</>;
        }
      },
      {
        title: '操作',
        render: (text, record, _, action) => {
          return (
            [
              <><Space>
                <a onClick={async () => {
                  setCurrentSource(record)
                  setShowSendConfirmDialog(true)
                }
                }>重发邮件</a>
                <a onClick={async () => {
                  setCurrentSource(record)
                  setShowDeleteSourceDialog(true)
                }
                }>删除</a></Space></>

            ]
          );
        }
      },
    ];

    const columns: ProColumns<API.Paper360>[] = [
      {
        title: '被评价人',
        dataIndex: 'name',
        hideInSearch: true,
      },
      {
        title: '被评价人邮箱',
        dataIndex: 'account',
        hideInSearch: true,
        ellipsis: true,
        width: 300,
      },
      {
        title: '评价人列表',
        dataIndex: 'answerUserList',
        hideInSearch: true,
        width: 600,
        render: (text, record, _, action) => {
          let users = text as API.Paper360AnswerUser[];
          return <Table showHeader={false} columns={answerUserColumns} dataSource={users} size={"small"}
                        pagination={false} bordered={true}/>
        }
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => {
          return (
            [
              (<a onClick={() => {
                setCurrentTarget(record)
                setShowDeleteTargetDialog(true)
              }}>删除</a>),
              (<a onClick={() => {
                setShowTargetAddUserDialog(true)
                setTimeout(() => {
                  targetAddUserFormRef?.current?.setFieldsValue({
                    targetId: record.id,
                  })
                })
              }}>新增评价人</a>),
              (<a onClick={() => {
                history.push(`/paperResult?id=${paperId}&targetId=${record.id}`)
              }}>答题情况</a>),
            ]
          );
        }
      },
    ]

    return (
      <div>
        <PageContainer>
          <Modal title="" visible={showSendConfirmDialog} confirmLoading={confirmLoading} onOk={async () => {
            setConfirmLoading(true)
            await sendEmail(paperId, currentSource?.id!)
            message.success("发送成功")
            setConfirmLoading(false)
            setShowSendConfirmDialog(false)
          }}
                 onCancel={() => setShowSendConfirmDialog(false)}>
            <p>确认给{currentSource?.name}重新发送邮件</p>
          </Modal>
          <Modal title="" visible={showDeleteSourceDialog} onOk={async () => {
            await deleteSource(paperId, currentSource?.id!)
            message.success("删除成功")
            ref.current?.reload();
            setShowDeleteSourceDialog(false)
          }}
                 onCancel={() => setShowDeleteSourceDialog(false)}>
            <p>确认给删除该被评价人</p>
          </Modal>
          <Modal title="" visible={showDeleteTargetDialog} onOk={async () => {
            await deleteTarget(paperId, currentTarget?.id!)
            message.success("删除成功")
            ref.current?.reload();
            setShowDeleteTargetDialog(false)
          }}
                 onCancel={() => setShowDeleteTargetDialog(false)}>
            <p>确认给删除该评价人</p>
          </Modal>
          <ModalForm<any>
            formRef={targetAddUserFormRef}
            title={"添加评价人"}
            visible={showTargetAddUserDialog}
            modalProps={{
              onCancel: () => setShowTargetAddUserDialog(false),
            }}

            onValuesChange={(changeValues) => {
              console.log(changeValues)
            }}

            onFinish={async (values) => {
              let data = await targetAddUser({...values, paperId})
              if (data.code == 200) {
                message.success("添加成功");
                ref.current?.reload();
                setShowTargetAddUserDialog(false)
              } else {
                message.error(data.message)
              }
              targetAddUserFormRef?.current?.resetFields()
            }}
          >
            <ProFormText name="targetId" hidden={true}/>
            <ProFormText name="account" label="评价人邮箱" rules={[{required: true}, {max: 50}, {
              pattern: /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/,
              message: '邮箱格式错误'
            }]}/>
            <ProFormText name="name" label="评价人姓名" rules={[{required: true}, {max: 20}]}/>
            <ProFormSelect
              options={[
                {
                  value: 1,
                  label: '下级',
                },
                {
                  value: 2,
                  label: '平级',
                },
                {
                  value: 3,
                  label: '上级',
                },
                {
                  value: 4,
                  label: '自评',
                },
              ]}
              name="relation"
              label={"关系"}
              rules={[{required: true}]}
            />
          </ModalForm>
          <ModalForm<any>
            formRef={addPaper360FormRef}
            title={isEdit ? "编辑环评" : "添加环评"}
            visible={showAddPaper360Dialog}
            modalProps={{
              onCancel: () => setShowAddPaper360Dialog(false),
            }}

            onFinish={async (values) => {
              let temp: API.Paper360AnswerUser[] = values['answerUsers']
              let answerUsers: API.Paper360AnswerUser[] = []
              temp.forEach(item => {
                if (item.name && item.account && (item.relation || 0) > 0) {
                  answerUsers.push(item)
                }
              })
              if (answerUsers.length <= 0) {
                message.error("评价人列表不能为空");
                return
              }

              let response = await addPaper360({...values, paperId, answerUsers})
              if (response.code == 200) {
                message.success("添加成功");
                ref.current?.reload();
                setShowAddPaper360Dialog(false)
              } else {
                message.error(response.message)
              }
              addPaper360FormRef?.current?.resetFields()
            }}
          >
            <ProForm.Group>
              <ProFormText name="targetAccount" label="被评价人邮箱" rules={[{required: true}, {max: 50}, {
                pattern: /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/,
                message: '邮箱格式错误'
              }]}/>
              <ProFormText name="targetName" label="被评价人姓名" rules={[{required: true}, {max: 20}]}/>
            </ProForm.Group>

            <ProForm.Item
              label={<Space><span>被评价人列表</span><a onClick={() => importEvaluator()}>批量导入</a><a
                href={"/template/evaluator.xls"}>下载模版</a></Space>}
              name="answerUsers"
              rules={[{required: true}]}
            >
              <EditableProTable<API.Paper360AnswerUser>
                rowKey="id"
                size={"small"}
                toolBarRender={false}
                bordered
                columns={[{
                  title: '邮箱',
                  dataIndex: 'account',
                  width: '35%',
                  formItemProps: {
                    rules: [
                      {
                        required: true,
                      },
                      {
                        max: 50
                      }, {
                        pattern: /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/,
                        message: '邮箱格式错误'
                      }
                    ],
                  },
                }, {
                  title: '姓名',
                  dataIndex: 'name',
                  width: '20%',
                  formItemProps: {
                    rules: [
                      {
                        required: true,
                      },
                      {
                        max: 30
                      }
                    ],
                  },
                },
                  {
                    title: '关系(与被评人)',
                    dataIndex: 'relation',
                    width: '20%',
                    valueType: 'select',
                    valueEnum: {
                      1: {
                        text: '下级'
                      },
                      2: {
                        text: '平级',
                      },
                      3: {
                        text: '上级',
                      },
                      4: {
                        text: '自评',
                      },
                    },
                    formItemProps: {
                      rules: [
                        {
                          required: true,
                        }
                      ],
                    },
                  },
                  {
                    title: '操作',
                    valueType: 'option',
                    width: 200,
                    render: (text, record, _, action) => [
                      <a
                        key="editable"
                        onClick={() => {
                          action?.startEditable?.(record!.id!);
                        }}
                      >
                        编辑
                      </a>,
                      <a
                        key="delete"
                        onClick={() => {
                          const tableDataSource = addPaper360FormRef.current?.getFieldValue('answerUsers') as API.Paper360AnswerUser[];
                          addPaper360FormRef.current?.setFieldsValue({
                            answerUsers: tableDataSource.filter((item) => item.id !== record.id),
                          });
                        }}
                      >
                        删除
                      </a>,
                    ],
                  },]}
                recordCreatorProps={{
                  newRecordType: 'dataSource',
                  position: 'bottom',
                  creatorButtonText: '新增评价人',
                  record: () => ({
                    id: Date.now(),
                    account: "",
                    name: "",
                  }),
                }}
              />
            </ProForm.Item>


          </ModalForm>

          <Card>
            <ProTable<API.Question>
              actionRef={ref}
              columns={columns}
              search={false}
              request={async (params = {}, sort, filter) => {
                const response = await paper360List(paperId);
                if (response.code === 200) {
                  return {
                    data: response.data!,
                    success: true,
                  };
                } else {
                  message.error(response.message)
                  return {}
                }
              }}
              editable={{
                type: 'multiple',
              }}
              rowKey={record => record.id!}
              pagination={false}
              dateFormatter="string"
              headerTitle="环评列表"
              toolBarRender={() => [
                <Button type="primary" key="primary" onClick={() => {
                  addPaper360FormRef?.current?.resetFields()
                  setShowAddPaper360Dialog(true)
                  setIsEdit(false)
                }}>
                  添加环评
                </Button>,]}
            />
          </Card>
        </PageContainer>
      </div>
    );
  }
;

export default Paper360List
