/* eslint-disable indent */
/* eslint-disable camelcase */
/* eslint-disable no-unused-expressions */
import React, { useState, useEffect } from 'react';
import {
  Drawer,
  Form,
  Input,
  notification,
  Row,
  Col,
  Select,
  Button,
  Dropdown,
  Tooltip,
  Menu,
  Space,
  Radio,
  Switch,
  TreeSelect,
  Tag,
  Upload,
  Modal,
  message,
} from 'antd';
import { UploadChangeParam } from 'antd/es/upload';
import { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import {
  PlusOutlined,
  DownOutlined,
  StepForwardFilled,
  InfoCircleOutlined,
  MinusCircleOutlined,
  LoadingOutlined,
  UploadOutlined,
  EyeOutlined,
  CloseOutlined,
} from '@ant-design/icons';

import FileViewer from 'react-file-viewer';
import { setAutoFreeze } from 'immer';
import styles from './optionEditModal.less';
import { EditDeviceConfig } from '@/services/maintenance/api';

import { loadEventFields,GetFieldValueFromTable } from '@/services/flow/flow';

import { GetTaskSyncField } from '@/services/PatrolFeedback/api';
import { reloadTableFields } from '@/services/tablemanager/tablemanager';
import Fieldselection from './optionEditComponents/Fieldselection';

import {
  GetCM_Event_LoadEventTable,
  CM_Event_LoadDepartmentAndRoles,
} from '@/services/standingBook/api';
import RMSComponents from '@/components/RolePmSite/index';

import ChangeAdd from './ChangeAdd';

import logo from '@/assets/images/icons/值映射.png';

const { Option } = Select;
const OptionEditModal = props => {
  const { callBackSubmit = () => { }, visible, type, formObj, keepTableData } = props;

  const [Type1, setType1] = useState('');
  const [showField, setShowField] = useState(false); // 选择字段弹窗
  const [filedList, setFiledList] = useState([]); // 全部字段数据
  const [fieldData, setFieldData] = useState([]); // 已选字段数据
  const [fieldName, setFieldName] = useState(''); // 字段选择类型名称

  const [standList, setStandList] = useState([]); //
  const [filterList, setFilterList] = useState([]); //
  const [filterOption, setFilterOption] = useState([]); //
  const [defaultValueOption, setDefaultValueOption] = useState([]); //

  const [loading, setLoading] = useState(false); // 上传按钮loading
  const [previewVisible, setPreviewVisible] = useState(false); // 预览文件弹窗
  const [fileType, setFileType] = useState(''); // 预览文件类型
  const [fileUrl, setFileUrl] = useState(''); // 预览文件路径 // 'http://192.168.10.167:8088/PandaWorkFlow/WorkFlow/AccountManage/DownloadFiles?filePath=520d9de3-b69b-42c0-bb65-f198a30d0cd4\\%E5%B7%A5%E5%8D%95%E6%97%B6%E9%99%90%E9%85%8D%E7%BD%AE.pdf',

  const [form] = Form.useForm();
  const [formAdd] = Form.useForm();
  const { Item } = Form;

  useEffect(() => {
    if (formObj) {
      form.setFieldsValue({ ...formObj });
      setStandList(JSON.parse(formObj.StandardConfig));
      formObj.FilterConfig && setFilterList(JSON.parse(formObj.FilterConfig));

      loadEventFields({
        eventTableName: formObj.AccountTableName,
      }).then(res => {
        console.log(res, 'ressssssssssssssss');
        const flattenedFieldNames = res.data.reduce((accumulator, currentValue) => {
          return accumulator.concat(currentValue.root.map(item => { return { value: item.fieldName, label: item.fieldName } }));
        }, []);
        setFilterOption(flattenedFieldNames)
        console.log(flattenedFieldNames, 'flattenedFieldNamesflattenedFieldNames');
      })
    }
  }, [visible]);

  const changedFieldName = (value,index) => {
    let list  = JSON.parse(JSON.stringify(filterList))
    list[index].fieldName = value
    list[index].defaultValue = ''
    console.log(list,'listlistlistlist');
    setFilterList(list)
  }
  const changedDefaultValue = (value,index) => {
    let list  = JSON.parse(JSON.stringify(filterList))
    list[index].defaultValue = value
    console.log(list,'listlistlistlist');
    setFilterList(list)
  }

  const getDefaultValueOption = (index) => {
    console.log(filterList,'filterListfilterListfilterList');
    GetFieldValueFromTable({
      fieldName: filterList[index].fieldName,
      tableName: formObj.AccountTableName
    }).then(res => {
      console.log(res,res.data.map(item => {
        return { value: item, label: item }
      }),'ressssssssssssssss');
      setDefaultValueOption(res.data.map(item => {
        return { value: item, label: item }
      }))
    })
  }

  const onSubmit = () => {
    form.validateFields().then(validate => {
      let data = validate;
      data.StandardConfig = JSON.stringify(standList);
      data.FilterConfig = JSON.stringify(filterList);
      EditDeviceConfig(data).then(res => {
        if (res.code === 0) {
          form.resetFields();
          callBackSubmit();
          notification.success({
            message: '提示',
            duration: 3,
            description: '编辑成功',
          });
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    });
  };

  // 字段配置
  const deployField = val => {
    let value = form.getFieldsValue(true);
    setFieldName(val);
    loadEventFields({
      eventTableName: formObj.AccountTableName,
    }).then(res => {
      if (res.code === 0) {
        let defaultCheckedList = value[val] ? value[val].split(',') : [];

        // 保存所有的字段用于右侧显示
        setFieldData(defaultCheckedList);
        let allFields = []; // 所有得字段用来判断是否为外部字段
        // 处理树形结构
        let checkList = res.data.map(item => {
          let plainOptions = [];
          // 存入没个组得字段
          item.root.forEach(ele => {
            plainOptions = [...plainOptions, ele.fieldName];
          });
          // 存所有得字段
          allFields = [...allFields, ...plainOptions];
          return {
            groupName: item.groupName,
            plainOptions,
            defaultCheckedList: [],
          };
        });
        let externalFields = {
          groupName: '外部字段',
          indeterminate: false,
          checkAll: true,
          plainOptions: [],
          defaultCheckedList: [],
        }; // 外部字段
        defaultCheckedList.forEach(item => {
          // 添加外部字段
          let isExternal = allFields.some(checkName => checkName === item);
          if (!isExternal) {
            externalFields.plainOptions.push(item);
            externalFields.defaultCheckedList.push(item);
          }
          checkList.forEach(element => {
            // 当前得模块是否有当前字段
            let indeterminate = element.plainOptions.some(checkName => checkName === item);
            // 处理已选中的字段
            if (indeterminate) {
              element.defaultCheckedList.push(item);
            }
            if (
              element.defaultCheckedList.length > 0 &&
              element.defaultCheckedList.length < element.plainOptions.length
            ) {
              element.indeterminate = true;
            } else {
              element.indeterminate = false;
            }
            // 处理是否全选字段
            if (element.defaultCheckedList.length === element.plainOptions.length) {
              element.checkAll = true;
            } else {
              element.checkAll = false;
            }
          });
        });
        // 添加外部字段
        if (externalFields.plainOptions.length > 0) {
          checkList.push(externalFields);
        }
        setFiledList(checkList);
        setTimeout(() => {
          setShowField(true);
        }, 0);
      }
    });
  };

  // 字段修改后回调函数
  const setFiled = val => {
    let Fields = '';
    val.forEach((item, index) => {
      if (index === val.length - 1) {
        Fields = `${Fields + item}`;
      } else {
        Fields = `${Fields + item},`;
      }
    });
    let obj = {};
    obj[fieldName] = Fields;
    form.setFieldsValue(obj);
    // saveOutFieldsLength(fieldName, filedList);
    setShowField(false);
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  const [fileList, setFileList] = useState([
    {
      uid: '-1',
      name: 'xxx.png',
      status: 'done',
      url: 'http://www.baidu.com/xxx.png',
    },
  ]);
  const handleChange = (file, item, index) => {
    if (file.file.status === 'done' && file.file.response.code === 0) {
      message.success('上传成功！');
      let list = JSON.parse(JSON.stringify(standList));
      list[index].pdfUrl = file.file.response.data;
      list[index].type = file.file.type.split('/')[1];
      setStandList(list);
    }
    let newFileList = [...file.fileList];

    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    newFileList = newFileList.slice(-2);

    // 2. Read from response and show file link
    newFileList = newFileList.map(files => {
      if (file.response) {
        // Component will show file.url as link
        files.url = file.response.url;
      }
      return files;
    });
    setFileList(newFileList);
  };
  const beforeUpload = (file, fileList) => {
    const isJpgOrPng =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/jpg' ||
      file.type === 'application/pdf';
    return new Promise((resolve, reject) => {
      if (!isJpgOrPng) {
        message.error('仅支持.jpg .png .pdf格式的文件');
        // message.error('支持.jpg .png .pdf ，单个文件不能超过20MB');
        reject(file);
      }
      if (file) {
        const size = file.size / 1024 / 1024;
        if (size > 20) {
          message.error('图片大小不能超过20M');
          reject(file);
        }
        resolve(file);
      }
    });
  };
  const setInputValue = (e, item, index) => {
    let list = JSON.parse(JSON.stringify(standList));
    list[index].name = e.currentTarget.value;
    setStandList(list);
  };
  const uprops = {
    action: `${window.origin}/PandaWorkFlow/WorkFlow/AccountManage/UploaderFiles`,
    // action: `http://192.168.10.167:8088/PandaWorkFlow/WorkFlow/AccountManage/UploaderFiles`,
    multiple: true,
  };

  const previewFile = file => { };

  const add = () => {
    let list = standList ? JSON.parse(JSON.stringify(standList)) : [];
    list.push({ name: '', pdfUrl: '' });
    setStandList(list);
  };
  const addFilterList = () => {
    let list = filterList ? JSON.parse(JSON.stringify(filterList)) : [];
    list.push({ fieldName: '', defaultValue: '' });
    setFilterList(list);
  };
  const remove = index => {
    let list = JSON.parse(JSON.stringify(standList));
    list.splice(index, 1);
    setStandList(list);
  };
  const removeFilterList = index => {
    let list = JSON.parse(JSON.stringify(filterList));
    list.splice(index, 1);
    setFilterList(list);
  };

  const preview = item => {
    setFileType(item.type);
    setFileUrl(
      `${`${window.origin}/PandaWorkFlow/WorkFlow/AccountManage/DownloadFiles?filePath=`}${item.pdfUrl
      }`,
      // `http://192.168.10.167:8088/PandaWorkFlow/WorkFlow/AccountManage/DownloadFiles?filePath=${
      //   item.pdfUrl
      // }`,
    );
    setPreviewVisible(true);
  };

  return (
    <Drawer
      title="设备档案库配置"
      visible={visible}
      destroyOnClose
      width="600px"
      {...props}
      footer={
        <Space>
          <Button onClick={onSubmit} type="primary">
            确定
          </Button>
        </Space>
      }
    >
      <Form form={form} labelCol={{ span: 7 }} style={{ overflowY: 'scroll' }}>
        <Row>
          <Col span={24}>
            <Item
              label="维保设备"
              name="AccountName"
              labelCol={{ span: 5 }}
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入业务名称',
            //   },
            //   {
            //     validator: (rule, value) => {
            //       let aa = form.getFieldValue().businessName;
            //       if (type === 'add' && keepTableData.indexOf(aa) != -1) {
            //         return Promise.reject('业务名称已存在');
            //       }
            //       if (
            //         type === 'edit' &&
            //         keepTableData.indexOf(aa) != -1 &&
            //         aa != formObj.businessName
            //       ) {
            //         return Promise.reject('业务名称已存在');
            //       }
            //       return Promise.resolve();
            //     },
            //   },
            // ]}
            >
              <Input placeholder="" disabled />
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="维保类型"
              name="DeviceType"
              labelCol={{ span: 5 }}
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入业务名称',
            //   },
            //   {
            //     validator: (rule, value) => {
            //       let aa = form.getFieldValue().businessName;
            //       if (type === 'add' && keepTableData.indexOf(aa) != -1) {
            //         return Promise.reject('业务名称已存在');
            //       }
            //       if (
            //         type === 'edit' &&
            //         keepTableData.indexOf(aa) != -1 &&
            //         aa != formObj.businessName
            //       ) {
            //         return Promise.reject('业务名称已存在');
            //       }
            //       return Promise.resolve();
            //     },
            //   },
            // ]}
            >
              <Input placeholder="" disabled />
            </Item>
          </Col>
          {/* <Col span={24}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <span>卡片字段</span>
                </div>
              }
              labelCol={{ span: 5 }}
            >
              <div style={{ display: 'flex' }}>
                <Form.Item name="CarField" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择卡片字段" allowClear />
                </Form.Item>
                <Button
                  type="dashed"
                  onClick={() => deployField('CarField')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col> */}
          <Col span={24}>
            <Item
              label={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  {/* <Tooltip title={`存在${summaryValue}个外部字段`}>
                    <InfoCircleOutlined
                      style={{
                        color: 'red',
                        display: summaryIsShow,
                      }}
                    />
                  </Tooltip> */}

                  <span>详情字段</span>
                </div>
              }
              // name="CarField"
              labelCol={{ span: 5 }}
            // rules={[
            //   {
            //     validator: (rule, value) => {
            //       console.log(checkedList1);
            //       let aa = form.getFieldValue().SummaryFields;
            //       let bb = [];
            //       console.log(aa.split(','));
            //       aa.split(',').map(i => {
            //         if (i != '') {
            //           bb.push(i);
            //         }
            //       });
            //       console.log(bb);
            //       if (aa == '') {
            //         return Promise.reject('摘要字段必选');
            //       }
            //       if (bb.length < 1 || aa.split(',').length > 5) {
            //         return Promise.reject('最少配置一个字段，最多配置五个字段');
            //       }
            //       return Promise.resolve();
            //     },
            //   },
            //   {
            //     required: true,
            //     message: '请选择摘要字段',
            //   },
            // ]}
            >
              <div style={{ display: 'flex' }}>
                <Form.Item name="DetailsField" style={{ marginBottom: 0, width: '100%' }}>
                  <Input placeholder="请选择详情字段" allowClear />
                </Form.Item>
                <Button
                  type="dashed"
                  onClick={() => deployField('DetailsField')}
                  icon={<PlusOutlined style={{ marginTop: '5px' }} />}
                  style={{ marginLeft: '10px', width: '70px' }}
                />
              </div>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="设备反馈"
              name="FeedbackNames"
              labelCol={{ span: 5 }}
            // rules={[
            //   {
            //     required: true,
            //     message: '请输入业务名称',
            //   },
            //   {
            //     validator: (rule, value) => {
            //       if (form.getFieldsValue().businessType == '') {
            //         return Promise.reject('业务类型必填');
            //       }
            //       return Promise.resolve();
            //     },
            //   },
            // ]}
            >
              <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                {formObj?.FeedbackNames?.map(item => (
                  <div>
                    <Tag color="success">{item}</Tag>
                  </div>
                ))}
                {formObj?.FeedbackNames?.length === 0 ? '暂无' : ''}
              </div>
            </Item>
          </Col>
          <Col span={24}>
            <Item
              label="第三方扫码"
              name="ThirdParty"
              labelCol={{ span: 5 }}
            >
              <Radio.Group>
                <Radio value={1}>是</Radio>
                <Radio value={0}>否</Radio>
              </Radio.Group>
            </Item>
          </Col>
          {/* <Col span={24}>
            <Item label="点检标准" name="docycle" labelCol={{ span: 5 }} />
          </Col> */}
          <Col span={24}>
            <Item label="点检标准" labelCol={{ span: 5 }}>
              <div>
                {standList?.length
                  ? standList.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        display: 'flex',
                        alignItems: 'flex-start',
                        justifyContent: 'center',
                        marginBottom: '5px',
                      }}
                    >
                      <Input
                        placeholder="请输入点检标准名称"
                        value={item.name}
                        onChange={e => {
                          setInputValue(e, item, index);
                        }}
                      />
                      <div className={styles.uploadBtn}>
                        <Upload
                          {...uprops}
                          onChange={value => handleChange(value, item, index)}
                          beforeUpload={beforeUpload}
                          previewFile={file => previewFile(file)}
                          maxCount={1}
                          showUploadList={false}
                        >
                          {item.pdfUrl ? (
                            <Button
                              style={{ marginLeft: '3px', width: '96px' }}
                              icon={<UploadOutlined />}
                            >
                              {item.pdfUrl.split('\\')[1]}
                            </Button>
                          ) : (
                            <Button
                              style={{ marginLeft: '3px', width: '96px' }}
                              icon={<UploadOutlined />}
                            >
                              上传
                            </Button>
                          )}
                        </Upload>
                      </div>
                      <EyeOutlined
                        onClick={() => preview(item)}
                        style={{ marginLeft: '10px', fontSize: '20px' }}
                      />
                      <MinusCircleOutlined
                        onClick={() => remove(index)}
                        style={{ marginLeft: '10px', fontSize: '20px' }}
                      />
                    </div>
                  ))
                  : null}
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                  style={{ marginLeft: '-2px', marginTop: '10px' }}
                >
                  再加一条
                </Button>
              </div>
            </Item>
          </Col>
          <Col span={24}>
            <Item label="筛选配置" labelCol={{ span: 5 }}>
              <div>
                {filterList?.length
                  ? filterList.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        display: 'flex',
                        alignItems: 'flex-start',
                        justifyContent: 'space-between',
                        marginBottom: '5px',
                      }}
                    >
                      <Select
                        defaultValue={item.fieldName}
                        style={{
                          width: 180,
                        }}
                        value={item.fieldName}
                        onChange={(value)=>changedFieldName(value,index)}
                        options={filterOption}
                      />
                      <div className={styles.uploadBtn}>
                        <Select
                          defaultValue={item.defaultValue}
                          style={{
                            width: 180,
                          }}
                          value={item.defaultValue}
                          onFocus={()=>getDefaultValueOption(index)}
                          onChange={(value)=>changedDefaultValue(value,index)}
                          options={defaultValueOption}
                        />
                      </div>
                      <MinusCircleOutlined
                        onClick={() => removeFilterList(index)}
                        style={{ marginLeft: '10px', fontSize: '20px' }}
                      />
                    </div>
                  ))
                  : null}
                <Button
                  type="dashed"
                  onClick={() => addFilterList()}
                  block
                  icon={<PlusOutlined />}
                  style={{ marginLeft: '-2px', marginTop: '10px' }}
                >
                  再加一条
                </Button>
              </div>
            </Item>
          </Col>
        </Row>
      </Form>
      <Fieldselection
        visible={showField}
        handleCancel={() => setShowField(false)}
        fieldList={filedList}
        onSubumit={val => setFiled(val)}
        fieldData={fieldData}
        fieldName={fieldName}
      />
      {/* <div>
        <FileViewer fileType={fileType} filePath={fileUrl} key={fileUrl} />
      </div> */}
      <div className={styles.mask} style={{ display: previewVisible ? 'block' : 'none' }}>
        <div className={styles.fileTitle}>
          <div>文件预览</div>
          <CloseOutlined onClick={() => setPreviewVisible(false)} />
        </div>
        <div className={styles.content}>
          <FileViewer fileType={fileType} filePath={fileUrl} key={fileUrl} />
        </div>
      </div>
    </Drawer>
  );
};
export default OptionEditModal;
