/* eslint-disable no-lonely-if */
/* eslint-disable no-else-return */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable camelcase */
import React, { useState, useEffect, useRef } from 'react';
import {
  Form,
  Input,
  Select,
  Tooltip,
  Button,
  notification,
  Drawer,
  Space,
  Modal,
  Row,
  Col,
  Switch,
} from 'antd';
import { PlusOutlined, InfoCircleOutlined, EyeOutlined } from '@ant-design/icons';
import { LoadEventFields } from '@/services/tablemanager/tablemanager';
import {
  GetCM_Ledger_LoadLedgerTable,
  GetCMLedger_QueryLedgers,
  Ledger_ReloadLedgerFields,
  Ledger_QueryLedger,
  Ledger_SaveLedger,
  Ledger_ParentLedgers,
} from '@/services/standingBook/api';
import { Account, getFieldInfo } from 'panda-xform';
import ChangeAdd from './changeAdd';
import EditTable from './EditTable';
import styles from './BookConfigNew.less';

const { Option } = Select;
const { TextArea } = Input;
const BookConfigNew = props => {
  const {
    callBackSubmit,
    type,
    formObj,
    visible,
    tableData,
    pickItem1,
    onCancel,
    data,
    maxLength,
    keepTableData,
  } = props;
  const [standingTable, setStandingTable] = useState([]);
  const [isVisible, setIsVisible] = useState(false); // 弹窗
  const [pickItem, setPickItem] = useState(''); // 选择的字段
  const [Order, setOrder] = useState(''); // 当前编辑序号
  const [filed, setFiled] = useState({}); // 传给子组件列表数据
  const [checkedList, setCheckedList] = useState([]);
  const [allFileds, setAllFileds] = useState([]); // 当前表所有的字段
  const [tbData, setTbData] = useState([]); // 当前表所有的字段
  const [tableShow, setTableShow] = useState(false); // 当前表所有的字段
  const [allData, setAllData] = useState([]); // 当前表所有的字段
  const [formJosn, setFormJosn] = useState([]); // 形态解析
  const [accountVisile, setAccountVisile] = useState(false); // 表单预览弹窗
  const [submitObj, setSubmitObj] = useState({}); // 表单预览弹窗
  const [modalLoading, setModalLoading] = useState(false); // 提交数据
  const [viewModalLoading, setViewModalLoading] = useState(false); // 表单预览弹窗
  const [parentData, setParentData] = useState([]); // 父级台账下拉框数据
  const [currentId, setCurrentId] = useState(''); // 新增成功后保存的ID
  const [form] = Form.useForm();
  const tableRef = useRef(null);
  const accountRef = useRef(null);
  const desabledArr = [
    'FileUpload',
    'Coordinate',
    'DrawPath',
    'DrawArea',
    'Device',
    'RelationForm',
  ];
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const formItemLayout = {
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 19,
    },
  };
  const itemLayout = {
    labelCol: {
      span: 10,
    },
    wrapperCol: {
      span: 14,
    },
  };
  const switchLayout = {
    labelCol: {
      span: 10,
    },
    wrapperCol: {
      span: 14,
    },
  };
  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    setModalLoading(true);
    form.validateFields().then(validate => {
      // return;
      if (validate) {
        let aa = form.getFieldsValue().Type;
        if (aa == '全部') {
          notification.warning({
            message: '提示',
            duration: 3,
            description: '分组名称不能为全部',
          });
        } else {
          let datas = JSON.parse(JSON.stringify(validate));
          for (let key in datas) {
            if (datas[key] === false) {
              datas[key] = 0;
            } else if (datas[key] === true) {
              datas[key] = 1;
            }
          }
          let obj =
            type === 'add' ? { ...datas, Order: maxLength } : { ...datas, Order, ID: formObj.ID };
          obj.LedgerFieids = tableRef.current.onFinish();
          currentId ? (obj.ID = currentId) : '';
          setSubmitObj(obj);
          Ledger_SaveLedger(obj)
            .then(res => {
              setModalLoading(false);
              if (res.code === 0) {
                // form.resetFields();
                // callBackSubmit();
                notification.success({
                  message: '提示',
                  duration: 3,
                  description: type === 'add' ? (currentId ? '编辑成功' : '新增成功') : '编辑成功',
                });
                if (type === 'add') {
                  setCurrentId(res.data);
                }
                setAccountVisile(true);
              } else {
                notification.error({
                  message: '提示',
                  duration: 3,
                  description: res.msg,
                });
              }
            })
            .catch(() => {
              notification.error({
                message: '提示',
                duration: 3,
                description: '网络异常请稍后再试',
              });
            });
        }
      }
    });
  };
  // 预览提交
  const viewSubmit = () => {
    setViewModalLoading(true);
    let arr = accountRef.current.getTableColumns();
    let viewArr = tableRef.current.onFinish();
    arr.map(item => {
      viewArr.map(ele => {
        if (item.dataIndex === ele.FieldName) {
          ele.ColumnWidth = item.width;
        }
      });
    });
    let obj = { ...submitObj, LedgerFieids: viewArr };
    currentId ? (obj.ID = currentId) : '';
    Ledger_SaveLedger(obj)
      .then(res => {
        setViewModalLoading(false);
        if (res.code === 0) {
          setAccountVisile(false);
          form.resetFields();
          callBackSubmit();
          notification.success({
            message: '提示',
            duration: 3,
            description: type === 'add' ? '新增成功' : '编辑成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      })
      .catch(() => {
        notification.error({
          message: '提示',
          duration: 3,
          description: '网络异常请稍后再试',
        });
      });
  };
  useEffect(() => {
    console.log(pickItem1);
    console.log(data[0]);
    if (visible) {
      // 获取台账表
      getTableData();
      if (type === 'edit') {
        Ledger_QueryLedger({ ledgerId: formObj.ID }).then(res => {
          if (res.code === 0) {
            // setTableShow(true)
            form.setFieldsValue(res.data);
            setOrder(res.data.Order);
            let editArr = res.data.LedgerFieids;
            changTable(res.data.TableName, editArr);
            // tableRef.current.setTableData(false, res.data.LedgerFieids);
          }
        });
      } else {
        if (!pickItem1 || pickItem1 == '全部') {
          form.setFieldsValue({ Type: data[0] });
        } else {
          form.setFieldsValue({ Type: pickItem1 });
        }
        form.setFieldsValue({ EnableTimeFilter: true });
        form.setFieldsValue({ EnableQuickSearch: true });
        form.setFieldsValue({ EnableBatchOperation: true });
        form.setFieldsValue({ EnableImportExport: true });
      }
      getParentData({ ledgerId: type === 'edit' ? formObj.ID : '0' });
    } else {
      setCurrentId('');
      setFiled({});
      form.resetFields();
      form.setFieldsValue({ AccountType: '台账' });
      setTbData([]);
      setAllData([]);
    }
  }, [visible]);

  // 获取父台账表
  const getParentData = params => {
    Ledger_ParentLedgers(params).then(res => {
      if (res.code === 0) {
        setParentData(res.data);
        console.log(res, 'ressssssssssssssssss');
      } else {
        setParentData([]);
      }
    });
  };

  // 获取台账表
  const getTableData = () => {
    GetCM_Ledger_LoadLedgerTable().then(res => {
      if (res.code === 0) {
        setStandingTable(res.data.root);
        if (type !== 'edit') {
          tableRef.current.setTableData(false, []);
        }
      }
    });
  };
  // const getFieldInfo = formJson => {
  //   let obj = {};
  //   let parent = formJson?.properties;
  //   if (isObject(parent)) {
  //     for (let v in parent) {
  //       let child = parent[v]?.properties;
  //       if (isObject(child)) {
  //         for (let s in child) {
  //           obj[s] = { ...child[s], ...widgetData[(child?.[s]?.widget)] };
  //         }
  //       }
  //     }
  //   }
  //   return obj;
  // };
  // const widgetData = {
  //   TextInput: {
  //     name: '文本',
  //     type: '文本控件',
  //   },
  //   TextArea: {
  //     name: '多行文本',
  //     type: '文本控件',
  //   },
  //   NumberInput: {
  //     name: '数值',
  //     type: '文本控件',
  //   },
  //   RichText: {
  //     name: '富文本',
  //     type: '文本控件',
  //   },
  //   Coding: {
  //     name: '编码',
  //     type: '文本控件',
  //   },
  //   SearchLocation: {
  //     name: '地址位置',
  //     type: '文本控件',
  //   },
  //   ComboBox: {
  //     name: '下拉框',
  //     type: '选择器控件',
  //   },
  //   RadioButton: {
  //     name: '单选框',
  //     type: '选择器控件',
  //   },
  //   CheckBox: {
  //     name: '复选框',
  //     type: '选择器控件',
  //   },
  //   SwitchSelector: {
  //     name: '开关按钮',
  //     type: '选择器控件',
  //   },
  //   RelevanceSelect: {
  //     name: '关联选择',
  //     type: '选择器控件',
  //   },
  //   CascadeSelector: {
  //     name: '联级选择',
  //     type: '选择器控件',
  //   },
  //   PersonSelector: {
  //     name: '人员选择',
  //     type: '业务控件',
  //   },
  //   DeptSelector: {
  //     name: '部门选择',
  //     type: '业务控件',
  //   },
  //   AccountSelector: {
  //     name: '台账选择',
  //     type: '业务控件',
  //   },
  //   DateTime: {
  //     name: '日期选择',
  //     type: '时间控件',
  //   },
  //   Time: {
  //     name: '时间选择',
  //     type: '时间控件',
  //   },
  //   FileUpload: {
  //     name: '附件',
  //     type: '附件控件',
  //   },
  //   Coordinate: {
  //     name: '地图坐标',
  //     type: 'GIS控件',
  //   },
  //   DrawPath: {
  //     name: '路径控件',
  //     type: 'GIS控件',
  //   },
  //   DrawArea: {
  //     name: '区域控件',
  //     type: 'GIS控件',
  //   },
  //   Device: {
  //     name: '设备选择',
  //     type: 'GIS控件',
  //   },
  //   RelationForm: {
  //     name: '关联表单',
  //     type: '高级控件',
  //   },
  //   AutoCalculate: {
  //     name: '自动计算',
  //     type: '高级控件',
  //   },
  // };
  const isObject = obj => typeof obj === 'object';

  // 切换表后数据处理为对应格式
  const changTable = (value, editArr = []) => {
    Ledger_ReloadLedgerFields({ tableName: value }).then(res => {
      if (res.data.LedgerFieids) {
        let fileMap = new Map();
        let initList = [];
        // 处理为子组件需要的格式
        res.data.LedgerFieids.forEach(item => {
          initList.push(item.FieldName);
          if (fileMap.has(item.Group)) {
            let list = [...fileMap.get(item.Group)];
            list.push(item.FieldName);
            fileMap.set(item.Group, list);
          } else {
            fileMap.set(item.Group, [item.FieldName]);
          }
        });

        const FormJson = getFieldInfo(JSON.parse(res.data.FormJson));
        let arr = res.data.LedgerFieids;
        arr.forEach(item => {
          item.Shape = FormJson[item.FieldName]?.name || item.Shape;
          item.widget = FormJson[item.FieldName]?.widget || 'TextInput';
          if (desabledArr.includes(item.widget)) {
            item.IsSort = 0;
            item.AccurateSearch = 0;
            item.LikeSearch = 0;
          }
        });
        if (editArr.length) {
          editArr.forEach(item => {
            item.Shape = FormJson[item.FieldName] ? FormJson[item.FieldName].name : item.Shape;
            item.widget = FormJson[item.FieldName]?.widget || 'TextInput';
            item.type = FormJson[item.FieldName]?.type || '文本控件';
            if (desabledArr.includes(item.widget)) {
              item.IsSort = 0;
              item.AccurateSearch = 0;
              item.LikeSearch = 0;
            }
          });
          tableRef.current.setTableData(false, editArr);
        } else {
          // Fields 切换表后清空台账字段和表数据
          form.setFieldsValue({ Fields: [] });
          tableRef.current.setTableData(false, []);
        }
        setFormJosn(FormJson);
        setAllData(arr);
        // FormJson
        // 给Map格式转为对象
        fileMap = Object.fromEntries(fileMap.entries());
        // 处理外部字段
        Object.keys(form.getFieldsValue()).forEach(key => {
          saveOutFieldsLength(key, initList);
        });
        setAllFileds(initList);
        setFiled(fileMap);
      }
    });
  };
  // 保存外部字段个数
  const saveOutFieldsLength = (key, initList) => {
    switch (key) {
      case 'Fields':
        form.setFieldsValue({ outListFileds: dealExternal(key, initList) });
        break;
      case 'SearchFields':
        form.setFieldsValue({ outSearchFields: dealExternal(key, initList) });
        break;
      case 'AddFields':
        form.setFieldsValue({ outAddFields: dealExternal(key, initList) });
        break;
      case 'EditFields':
        form.setFieldsValue({ outEditFields: dealExternal(key, initList) });
        break;
      case 'WebFields':
        form.setFieldsValue({ outWebFields: dealExternal(key, initList) });
        break;
      case 'MobileFields':
        form.setFieldsValue({ outMobileFields: dealExternal(key, initList) });
        break;
      default:
        break;
    }
  };
  // 选择字段回调函数
  const onOK = prop => {
    setIsVisible(false);
    let obj = {};
    obj[prop.pickItem] = prop.str;
    let allArr = prop.str.split(',');
    let showArr = prop.str.split(',');
    let editArr = tableRef.current.onFinish().map(item => {
      return item.FieldName;
    });
    showArr = showArr.filter(item => {
      return !editArr.includes(item);
    });
    let tableArr = tableRef.current.onFinish().concat(
      allData.filter(item => {
        return showArr.includes(item.FieldName);
      }),
    );
    let arr = [];
    allArr.map(item => {
      tableArr.map(ele => {
        if (item === ele.FieldName) {
          arr.push(ele);
        }
      });
    });
    tableRef.current.setTableData(
      false,
      // tableArr.filter(item => {
      //   return allArr.includes(item.FieldName);
      // }),
      arr,
    );
    form.setFieldsValue(obj);
    saveOutFieldsLength(prop.pickItem, allFileds);
  };
  // 处理外部字段
  const dealExternal = (fileds, list) => {
    let isExternal;
    let externalLength = 0;
    if (form.getFieldValue(fileds).length) {
      form
        .getFieldValue(fileds)
        .split(',')
        .forEach(item => {
          isExternal = list.some(val => val === item);
          if (!isExternal && item !== '') {
            // eslint-disable-next-line no-plusplus
            externalLength++;
          }
        });
    }

    return externalLength;
  };
  // 勾选字段
  const pickFiled = fileds => {
    if (!form.getFieldValue('TableName')) {
      notification.error({ message: '提示', duration: 3, description: '请选择台账表' });
      return;
    }
    // 添加外部字段
    let fil = { ...filed };
    fil['外部字段'] = [];
    let isExternal;
    let list = form.getFieldValue(fileds).length ? form.getFieldValue(fileds).split(',') : [];
    list.forEach(item => {
      isExternal = allFileds.some(val => val === item);
      if (!isExternal && item !== '') {
        fil['外部字段'].push(item);
      }
    });
    if (fil['外部字段'].length === 0) {
      delete fil['外部字段'];
    }
    setFiled(fil);
    setCheckedList(list);
    setPickItem(fileds);
    setIsVisible(true);
  };
  // 搜索框监听
  const onSearch = value => {
    if (value) {
      form.setFieldsValue({ Type: value });
    }
  };
  // 表单值监听
  const handleValuesChange = (changedValues, allValues) => {
    if ('TableName' in changedValues) {
      let AccountType = standingTable.filter(item => {
        return item.value === changedValues.TableName;
      })[0].text;
      form.setFieldsValue({ AccountType });
    }
  };

  return (
    <Modal
      title={
        <div className={styles.modalTitle}>
          <div>{type === 'add' ? '台账配置' : '台账编辑'}</div>
          {/* <div>
            <Button
              type="primary"
              ghost
              icon={<EyeOutlined />}
              onClick={() => setAccountVisile(true)}
              style={{ marginLeft: '10px' }}
            >
              预览
            </Button>
          </div> */}
        </div>
      }
      visible={visible}
      destroyOnClose
      onOk={onSubmit}
      onCancel={onCancel}
      centered
      bodyStyle={{ width: '100%', height: '800px', overflowY: 'scorll' }}
      width="1600px"
      // style={{ top: '-20px' }}
      getContainer={false}
      // style={{
      //   maxWidth: '100vw',
      //   top: 0,
      //   paddingBottom: 0,
      // }}
      // bodyStyle={{
      //   height: 'calc(100vh - 55px - 53px)',
      //   overflowY: 'auto',
      // }}
      // width="100vw"
      confirmLoading={modalLoading}
      okText="保存并查看"
    >
      <div className={styles.top}>
        <Form form={form} {...layout} onValuesChange={handleValuesChange}>
          <Row>
            <Col span={8}>
              <Item
                label="台账名称"
                name="Name"
                rules={[
                  {
                    required: true,
                    validator: (rule, value) => {
                      if (
                        keepTableData.find(i => i.name == form.getFieldsValue().Name) &&
                        form.getFieldsValue().Name != formObj.name
                      ) {
                        return Promise.reject('台账名称已存在');
                      } else if (form.getFieldsValue().Name == '') {
                        return Promise.reject('台账名称不能为空');
                      }
                      return Promise.resolve();
                    },
                  },
                ]}
              >
                <Input placeholder="台账名称不可重复" allowClear />
              </Item>
            </Col>
            <Col span={8}>
              <Item
                label="父级台账"
                name="PreName"
                // rules={[{ required: true, message: '请选择分组' }]}
              >
                <Select
                  showSearch
                  filterOption={false}
                  // onSearch={onSearch}
                  placeholder="请选择父级台账"
                  allowClear
                >
                  {parentData.map((item, index) => (
                    <Option value={item.name} key={index}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col span={4}>
              <Item
                label="台账分组"
                name="Type"
                rules={[{ required: true, message: '请选择分组' }]}
                {...itemLayout}
              >
                <Select
                  showSearch
                  filterOption={false}
                  onSearch={onSearch}
                  placeholder="请输入分组名称"
                  allowClear
                >
                  {data.map((item, index) => (
                    <Option value={item} key={index}>
                      {item}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col span={4}>
              <Item
                label="台账类型"
                name="AccountType"
                rules={[{ required: true, message: '请选择类型' }]}
                {...itemLayout}
              >
                <Select placeholder="请选择台账类型" disabled>
                  <Option value="台账">台账</Option>
                  <Option value="反馈">反馈</Option>
                  <Option value="设备">设备</Option>
                </Select>
              </Item>
            </Col>
            <Col span={8}>
              <Item
                label="台账主表"
                name="TableName"
                rules={[{ required: true, message: '请选择台账表' }]}
              >
                <Select
                  placeholder=""
                  optionFilterProp="children"
                  onChange={changTable}
                  showSearch
                  disabled={type !== 'add'}
                >
                  {standingTable.map((item, index) => (
                    <Option key={index} value={item.value}>
                      {item.value}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col span={8}>
              <Item
                {...formItemLayout}
                label={
                  <>
                    {form.getFieldValue('outListFileds') > 0 ? (
                      <Tooltip title={`外部字段${form.getFieldValue('outListFileds')}个`}>
                        <InfoCircleOutlined style={{ color: 'red', margin: '2px 3px 0 3px' }} />
                      </Tooltip>
                    ) : (
                      ''
                    )}
                    <span>台账字段</span>
                  </>
                }
                name="Fields"
                rules={[{ required: true, message: '请选择台账字段' }]}
              >
                <div style={{ display: 'flex' }}>
                  <Form.Item name="Fields" style={{ marginBottom: 0, width: '100%' }}>
                    <TextArea
                      placeholder="前端详情查看字段"
                      allowClear
                      style={{ height: '32px' }}
                    />
                  </Form.Item>
                  <Button
                    type="dashed"
                    style={{ width: '50px', marginLeft: '10px' }}
                    icon={<PlusOutlined />}
                    onClick={() => {
                      pickFiled('Fields');
                    }}
                  />
                </div>
              </Item>
            </Col>
            <Col span={8}>
              <Item label="接口配置" name="Interface">
                <Input placeholder="服务项目dll库" allowClear />
              </Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="时间筛选"
                name="EnableTimeFilter"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="快速检索"
                name="EnableQuickSearch"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="站点过滤"
                name="EnableSiteFilter"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="导入导出"
                name="EnableImportExport"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="批量操作"
                name="EnableBatchOperation"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                {...switchLayout}
                valuePropName="checked"
                // style={{ marginBottom: '0', padding: '2px', borderBottom: '1px solid #ccc' }}
                label="打印功能"
                name="EnablePrint"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <ChangeAdd
          visible={isVisible}
          onCancel={() => {
            setIsVisible(false);
            setCheckedList([]);
          }}
          callBackSubmit={onOK}
          newCheckedList={checkedList}
          filed={filed}
          pickItem={pickItem}
          formObj={formObj}
        />
      </div>
      <div className={styles.bottom}>
        <EditTable visible={tableShow} ref={tableRef} tbData={tbData} formObj={formObj} />
      </div>
      <Modal
        title="台账预览"
        visible={accountVisile}
        destroyOnClose
        onOk={viewSubmit}
        onCancel={() => {
          setAccountVisile(false);
          callBackSubmit();
        }}
        centered
        bodyStyle={{ width: '100%', height: '800px', overflowY: 'scorll' }}
        width="1600px"
        confirmLoading={viewModalLoading}
        // okText=
      >
        <Account ref={accountRef} accountName={form.getFieldValue('Name')} notUse={'other,edit,add,del'} />
      </Modal>
    </Modal>
  );
};
export default BookConfigNew;
