import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { Divider, Tooltip, Switch, Select, Input, message } from 'antd';
import lodash from 'lodash';
import { PlusOutlined, PlusCircleOutlined, DeleteOutlined } from '@ant-design/icons';
import RuleConfig from '@/components/RuleConfig';
import PeopleSelector from '@/components/PeopleSelector';
import { GetFormDataSource, GetRoleUserNew } from '@/services/workflow/workflow';
import styles from '../NodeModal.less';

let chnNumChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
let chnUnitSection = ['', '万', '亿', '万亿', '亿亿'];
let chnUnitChar = ['', '十', '百', '千'];

const ConfigCopyPerson = (props, ref) => {
  const { nodeChage, editMsg, flowID, flowData } = props;
  const [showPersonSelect, setShowPersonSelect] = useState(false); // 是否显示人员选择器
  const TurnOnCc = useRef(0);
  const [fieldList, setFieldList] = useState([]); // 当规则字段
  const [ruleIndex, setRuleIndex] = useState(); // 编辑当前规则索引
  const allFieldList = useRef([]); // 所有字段列表
  const talbeList = useRef([]);
  const [showRule, setShowRule] = useState(false); // 是否显示节点扭转规则弹窗
  const RuleList = useRef([]); // 规则配置列表
  const [flag, setFlag] = useState(0); // 用于刷新界面

  useImperativeHandle(ref, () => ({
    getParmar,
  }));

  useEffect(() => {
    if (JSON.stringify(editMsg) === '{}') {
      return;
    }
    allFieldList.current = [];
    talbeList.current = [];
    TurnOnCc.current = 0;
    TurnOnCc.current = editMsg.TurnOnCc;
    RuleList.current = editMsg.CCRuleList || [];
    // 获取表数据
    GetFormDataSource({ flowID }).then(res => {
      let list = new Set(talbeList.current);
      allFieldList.current = [];
      res.data.forEach(item => {
        if (!allFieldList.current.some(ele => ele.TableName === item.TableName)) {
          let data = item.TableFieldNames.filter(i => i !== '关联表单');
          allFieldList.current.push({
            TableFieldNames: data,
            TableName: item.TableName,
          });
        }
        list.add(item.TableName);
      });
      talbeList.current = [...list];
    });
    setFlag(flag + 1);
  }, [editMsg]);
  const getParmar = () => ({ CCRuleList: RuleList.current });

  // 配置当前节点抄送人
  const editCC = index => {
    setRuleIndex(index);
    setShowPersonSelect(true);
  };

  const onChange = e => {
    if (e) {
      TurnOnCc.current = 1;
    } else {
      TurnOnCc.current = 0;
    }
    nodeChage('TurnOnCc', TurnOnCc.current);
    setFlag(flag + 1);
  };

  // 规则回填
  const saveRule = e => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    list[ruleIndex].RuleContent = e;
    RuleList.current = list;
    nodeChage('CCRuleList', list);
    setShowRule(false);
  };

  // 选择人员回填
  const savePerson = val => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    let useId = val.person?.map(i => i.value);
    let roleId = val.role?.map(i => i.value);
    list[ruleIndex].UserIds = useId.toString();
    list[ruleIndex].RoleIds = roleId.toString();
    list[ruleIndex].PersonList = [...val.person, ...val.role];
    list[ruleIndex].UserList = val.person;
    list[ruleIndex].RoleList = val.role;
    RuleList.current = list;
    nodeChage('CCRuleList', list);
    setShowPersonSelect(false);
  };

  // 网关表单配置监听
  const formChage = (e, index, field) => {
    let list = lodash.cloneDeep(RuleList.current);
    if (field === 'RuleName') {
      e.persist();
      list[index][field] = e.target.value;
    }
    RuleList.current = list;
    nodeChage('CCRuleList', list);
    setFlag(flag + 1);
  };

  // 配置当前规则
  const editRule = (msg, index) => {
    let listfleld = talbeList.current;
    let list = [
      {
        TableFieldNames: [
          '上报人名称',
          '上报人部门',
          '上报站点',
          '处理站点',
          '更新时间',
          '上报时间',
        ],
        TableName: '内部字段',
      },
    ];
    listfleld.forEach(item => {
      let obj = allFieldList.current.find(ele => ele.TableName === item);
      if (obj.TableName && obj.TableFieldNames?.length > 0) {
        list.push({
          TableFieldNames: obj.TableFieldNames,
          TableName: obj.TableName,
        });
      }
    });
    list.push({
      TableFieldNames: ['撤回', '回退', '转办', '移交', '挂起', '解挂', '中途关单'],
      TableName: '操作动作',
    });
    setFieldList(list);
    setRuleIndex(index);
    setShowRule(true);
  };

  // 删除规则
  const deleRule = index => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    list.splice(index, 1);
    RuleList.current = list;
    nodeChage('CCRuleList', list);
    setFlag(flag + 1);
  };
  // 数字转中文
  const SectionToChinese = section => {
    let strIns = '';
    let chnStr = '';
    let unitPos = 0;
    let zero = true;
    while (section > 0) {
      let v = section % 10;
      if (v === 0) {
        if (!zero) {
          zero = true;
          chnStr = chnNumChar[v] + chnStr;
        }
      } else {
        zero = false;
        strIns = chnNumChar[v];
        strIns += chnUnitChar[unitPos];
        chnStr = strIns + chnStr;
      }
      // eslint-disable-next-line no-plusplus
      unitPos++;
      section = Math.floor(section / 10);
    }
    return chnStr;
  };
  // 数字转中文
  const NumberToChinese = num => {
    let unitPos = 0;
    let strIns = '';
    let chnStr = '';
    let needZero = false;

    if (num === 0) {
      return chnNumChar[0];
    }

    while (num > 0) {
      let section = num % 10000;
      if (needZero) {
        chnStr = chnNumChar[0] + chnStr;
      }
      strIns = SectionToChinese(section);
      strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0];
      chnStr = strIns + chnStr;
      needZero = section < 1000 && section > 0;
      num = Math.floor(num / 10000);
      // eslint-disable-next-line no-plusplus
      unitPos++;
    }

    return chnStr;
  };

  // 添加规则
  const addRule = () => {
    let list = JSON.parse(JSON.stringify(RuleList.current));
    list.push({
      RuleContent: '',
      RuleName: '',
      PersonList: [],
      UserIds: [],
      RoleIds: [],
      UserList: [],
      RoleList: [],
    });
    RuleList.current = list;
    nodeChage('CCRuleList', list);
    setFlag(flag + 1);
  };

  return (
    <div>
      <Divider
        orientation="left"
        style={{
          borderTopColor: '#99bbe8',
          color: '#15428b',
          fontWeight: 700,
        }}
      >
        节点抄送
      </Divider>
      <div style={{ display: 'flex', justifyContent: 'right', marginBottom: '12px' }}>
        允许抄送
        <Switch
          style={{ marginLeft: '5px' }}
          checked={TurnOnCc.current !== 0}
          onChange={onChange}
        />
      </div>
      <div className={styles.titleBox}>
        当开启”允许抄送“后，本节点具备抄送功能： 配置不同的抄送规则，可抄送给指定人员；
        当不配置规则的时候，则默认本届点任何办理操作都会抄送给指定人员。
      </div>
      <div
        className={styles.btnAddRule}
        onClick={addRule}
        style={{ display: TurnOnCc.current === 1 ? 'flex' : 'none' }}
      >
        <PlusCircleOutlined style={{ marginRight: '10px' }} />
        添加规则
      </div>
      <div className={styles.ruleContent}>
        {RuleList.current.map((item, index) => (
          <div className={styles.ruleBox} key={index}>
            <div
              className={styles.ruleTitle}
              style={{ display: TurnOnCc.current === 1 ? 'flex' : 'none' }}
            >
              <div className={styles.textContet}>规则{NumberToChinese(index + 1)}</div>
              <DeleteOutlined style={{ cursor: 'pointer' }} onClick={() => deleRule(index)} />
            </div>
            <div
              className={styles.formBox}
              style={{ display: TurnOnCc.current === 1 ? 'flex' : 'none' }}
            >
              <div className={styles.label}>规则名称：</div>
              <div className={styles.item}>
                <Input
                  style={{ width: '100%' }}
                  value={item.RuleName}
                  placeholder="请输入规则名称"
                  onChange={e => {
                    formChage(e, index, 'RuleName');
                  }}
                />
              </div>
            </div>
            <div
              className={styles.buttonBox}
              style={{ display: TurnOnCc.current === 1 ? 'flex' : 'none', marginBottom: '10px' }}
              onClick={() => editCC(index)}
            >
              <div
                className={styles.setButton}
                style={{ textAlign: item.PersonList ? 'left' : 'center' }}
              >
                <Tooltip
                  title={
                    item.PersonList?.length > 0 &&
                    item.PersonList?.map(item => item.label).join(',')
                  }
                >
                  <span>
                    {item.PersonList?.length > 0
                      ? item.PersonList?.map(item => item.label).join(',')
                      : '选择抄送人'}
                  </span>
                </Tooltip>
              </div>
              <div className={styles.addIcon}>
                <PlusOutlined />
              </div>
            </div>
            <div
              className={styles.buttonBox}
              onClick={() => editRule(item, index)}
              style={{ display: TurnOnCc.current === 1 ? 'flex' : 'none' }}
            >
              <div
                className={styles.setButton}
                style={{ textAlign: item.RuleContent ? 'left' : 'center' }}
              >
                <Tooltip title={item.RuleContent}>
                  <span>{item.RuleContent ? item.RuleContent : '设置条件'} </span>
                  {/* <span>{item.RuleContent} </span> */}
                </Tooltip>
              </div>
              <div className={styles.addIcon}>
                <PlusOutlined />
              </div>
            </div>
          </div>
        ))}
      </div>
      <RuleConfig
        RuleContent={RuleList.current[ruleIndex]?.RuleContent}
        fieldList={fieldList}
        visible={showRule}
        handleCancel={() => setShowRule(false)}
        onSubumit={e => saveRule(e)}
        flag={1}
        flowID={flowID}
      />

      <PeopleSelector
        visible={showPersonSelect}
        userIds={RuleList.current[ruleIndex]?.UserList}
        roleIds={RuleList.current[ruleIndex]?.RoleList}
        onCancel={() => setShowPersonSelect(false)}
        onSubumit={e => savePerson(e)}
      />
    </div>
  );
};

export default forwardRef(ConfigCopyPerson);
