import React, { useState, useRef, useEffect } from "react";
import { connect } from "react-redux";
import { Modal, Form, Notification, Tooltip, Upload, Button, Checkbox, CheckboxGroup, Collapse } from "@douyinfe/semi-ui";
import { IconUpload } from '@douyinfe/semi-icons';
import moment from "moment";


const AutomaticModal = ({ actions, dispatch, apiRoot, qiniuUrl, visible, eidtData, close, success, projectList }) => {

   const { service, problem } = actions;
   const form = useRef();//表单
   const [strucData, setStrucData] = useState([])  //结构物数据

   const [projectId, setProjectId] = useState();    //项目id
   const [structId, setStructId] = useState();      //结构物id
   const [factorId, setFactorId] = useState([]);     //监测因素id
   const [factorList, setFactorList] = useState([]);     //监测因素
   const [factorChech, setFactorChech] = useState([]);     //选中的监测因素
   const [activeKey, setActiveKey] = useState([]);     //
   const [correlationId, setCorrelationId] = useState([]);     //


   useEffect(async () => {
      if (eidtData?.id) {
         console.log(eidtData);
         setProjectId(eidtData?.projectId)
         setStructId(eidtData?.structId)
         setFactorId(eidtData?.factors?.map(s => s.codeName) || [])

         let data = await getData(eidtData?.projectId)
         let Factor = data?.find(s => s.strucId == eidtData?.structId)?.factor || []
         setFactorList(Factor)
         setFactorChech(Factor?.filter(s => eidtData?.factors?.map(s => s.codeName)?.includes(s.proto)))
         // setActiveKey(eidtData?.factors?.map(s => s.codeName) || [])
      }
   }, [])

   const getData = async (projectId) => {
      let data = []
      await dispatch(service.getFactorList({ pepProjectId: projectId })).then((res) => {
         if (res.success) {
            setStrucData(res.payload.data)
            data = res.payload.data
         }
      })
      return data
   }

   return (
      <>
         <Modal
            title={eidtData.id ? "编辑生成规制" : '新增生成规制'}
            okText="确定"
            cancelText="取消"
            visible={visible}
            onOk={() => {

               form.current.validate().then((v) => {
                  let data = {
                     id: eidtData?.id,
                     reportName: v.reportName,
                     projectId: v.projectId,
                     projectName: v.projectName,
                     reportType: v.reportType,
                     reportPicPath: v.reportPicPath[0]?.response?.url,
                     framer: v.framer,
                     auditor: v.auditor,
                     ratifier: v.ratifier,
                     structId: v.structId,
                     projectOverview: v.projectOverview,
                     reportStartTime: moment(v.reportTime[0]).format('YYYY-MM-DD HH:mm:ss'),
                     reportEndTime: moment(v.reportTime[1]).format('YYYY-MM-DD HH:mm:ss'),
                     time: eidtData?.time && moment(eidtData?.time).format('YYYY-MM-DD HH:mm:ss') || null,
                     factors: []
                  }

                  v.factorId?.forEach(d => {
                     let index = d.length
                     let factorData = {}
                     for (let key in v) {
                        factorData.codeName = d
                        factorData.tempName = factorData.tempName || []
                        if (key?.indexOf(d) != -1) {
                           if (key?.slice(index) == 'pointDescrip') factorData.pointDescrip = v[key]
                           if (key?.slice(index) == 'pointPicPath') factorData.pointPicPath = v[key] && v[key][0]?.response?.url
                           if (key?.slice(index) == 'factorDescrip') factorData.factorDescrip = v[key]
                           if (key?.slice(index) == 'sensorNames') factorData.sensorNames = factorChech?.find(p => p.proto == d)?.sensor?.filter(f => v[key]?.includes(f.id))?.map(c => ({ id: c.id, name: c.name })) || []
                           if (key?.slice(index) == 'startEndTime') {
                              factorData.startTime = v[key] && moment(v[key][0]).format('YYYY-MM-DD HH:mm:ss')
                              factorData.endTime = v[key] && moment(v[key][1]).format('YYYY-MM-DD HH:mm:ss')
                           }
                           if (key?.slice(index) == 'tempName1') {
                              factorData.tempName?.push({
                                 index: 1,
                                 id: v[key],
                                 name: factorChech?.find(p => p.proto == d)?.sensor?.find(f => v[key] == f.id)?.name
                              })
                           }
                           if (key?.slice(index) == 'tempName2') {
                              factorData.tempName?.push({
                                 index: 2,
                                 id: v[key],
                                 name: factorChech?.find(p => p.proto == 1004)?.sensor?.find(f => v[key] == f.id)?.name
                              })
                           }
                           if (key?.slice(index) == 'factorDescrip') factorData.factorDescrip = v[key]
                           // if (key?.slice(index) == 'glStaName') factorData.glStaName = v[key]
                           // if (key?.slice(index) == 'tempStaName') factorData.tempStaName = v[key]
                           if (key?.slice(index) == 'initialTime') factorData.initialTime = v[key] && moment(v[key]).format('YYYY-MM-DD HH:mm:ss')
                           if (key?.slice(index) == 'releTime') {
                              factorData.releStartTime = v[key] && moment(v[key][0]).format('YYYY-MM-DD HH:mm:ss')
                              factorData.releEndTime = v[key] && moment(v[key][1]).format('YYYY-MM-DD HH:mm:ss')
                           }
                        }
                     }
                     factorData.glStaName = factorData?.tempName?.find(s => s.index == 1)?.name
                     factorData.tempStaName = factorData?.tempName?.find(s => s.index == 2)?.name || factorData?.tempName?.find(s => s.index == 1)?.name
                     data.factors?.push(factorData)
                  })

                  dispatch(service.postAutomaticReport(data)).then((res) => {
                     if (res.success) {
                        close()
                        success()
                     }
                  })

               })
            }}
            width={700}
            onCancel={() => close()}
         >
            <Form
               labelPosition="left"
               labelAlign="right"
               labelWidth="150px"
               onValueChange={(values, field) => { }}
               getFormApi={(formApi) => (form.current = formApi)}
            >
               <Form.Input field="reportName" label='报表名称' style={{ width: 300 }} placeholder="请输入报表名称" showClear
                  initValue={eidtData?.reportName || ""}
                  rules={[{ required: true, message: "请输入报表名称,15字以内", max: 15 }]}
               />
               <Form.Select label="所属项目" field="projectId" placeholder="请选择项目" showClear style={{ width: 300 }} filter
                  initValue={eidtData?.projectId || ""}
                  rules={[{ required: true, message: "请选择项目" }]}
                  onChange={v => {
                     setProjectId(v)
                     getData(v)
                     form.current.setValue('structId', null)
                     setStructId("")
                     setFactorList([])
                     form.current.setValue('factorId', [])
                     setFactorChech([])
                  }} >
                  {projectList?.map((item) => {
                     return <Form.Select.Option value={item.id} label={item.name || item.pepProjectName}></Form.Select.Option>

                  })}
               </Form.Select>
               <Form.Input field="projectName" label='项目名称' style={{ width: 300 }} placeholder="请输入项目名称" showClear
                  initValue={eidtData?.projectName || ""}
                  rules={[{ required: true, message: "请输入项目名称,15字以内", max: 15 }]}
               />
               <Form.Select label="报表类型" field="reportType" placeholder="请选择报表类型" showClear style={{ width: 300 }}
                  rules={[{ required: true, message: "请选择报表类型" }]}
                  initValue={eidtData?.reportType || ""}
                  optionList={[{ value: "月报表", label: "月报表" }, { value: "季报表", label: "季报表" }, { value: "年报表", label: "年报表" }]}
               />
               <Form.Upload label="首页图片" field="reportPicPath" style={{ display: 'inline-block', }}
                  initValue={eidtData?.reportPicPath && [{ url: `/_file-server/${eidtData?.reportPicPath?.slice(qiniuUrl.length + 1)}`, name: eidtData.reportPicPath?.split('/')?.pop(), status: 'success', preview: ['png', 'jpg', 'jpeg'].includes(eidtData.reportPicPath?.split('.')?.pop()?.replace('.', '')) }] || null}
                  rules={[{ required: true, message: "请上传首页图片" }]}
                  action={`${apiRoot}/attachments/p`}
                  accept={'.txt, .doc, .docx, .xls, .xlsx, .pdf, .png, .jpg, .rar, .zip'}
                  limit={1} maxSize={5120}
               >
                  <Button icon={<IconUpload />} theme="light">
                     文件上传
                  </Button>
               </Form.Upload>
               <Form.Input field="framer" label='制定者' style={{ width: 300 }} placeholder="请输入制定者" showClear
                  initValue={eidtData?.framer || ""}
                  rules={[{ required: true, message: "请输入制定者" }]}
               />
               <Form.Input field="auditor" label='审核者' style={{ width: 300 }} placeholder="请输入审核者" showClear
                  initValue={eidtData?.auditor || ""}
                  rules={[{ required: true, message: "请输入审核者" }]}
               />
               <Form.Input field="ratifier" label='批准者' style={{ width: 300 }} placeholder="请输入批准者" showClear
                  initValue={eidtData?.ratifier || ""}
                  rules={[{ required: true, message: "请输入批准者" }]}
               />

               <Form.Select label="结构物" field="structId" placeholder="请选择结构物" showClear style={{ width: 300 }} filter
                  rules={[{ required: true, message: "请选择结构物" }]} disabled={projectId ? false : true}
                  initValue={eidtData?.structId || ""}
                  onChange={v => {
                     setFactorList(strucData?.find(s => s.strucId == v)?.factor || [])
                     setStructId(v)
                     form.current.setValue('factorId', [])
                     setFactorChech([])
                  }} >
                  {strucData?.map((item) => {
                     return <Form.Select.Option value={item.strucId} label={item.strucName}></Form.Select.Option>

                  })}
               </Form.Select>

               <Form.TextArea field="projectOverview" label='报表描述' style={{ width: 420 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入报表描述" showClear
                  initValue={eidtData?.projectOverview || ""}
                  rules={[{ required: true, message: "请输入报表描述" }]}
               />
               <Form.DatePicker field='reportTime' label='开始结束时间' type='dateTimeRange' showClear
                  initValue={eidtData?.reportStartTime && [moment(eidtData?.reportStartTime).format('YYYY-MM-DD HH:mm:ss'), moment(eidtData?.reportEndTime).format('YYYY-MM-DD HH:mm:ss')] || null}
                  rules={[{ required: true, message: "请选择开始结束时间" }]}
               />
               <Form.Select label="包含的监测因素" field="factorId" placeholder="请选择监测因素" showClear style={{ width: 300 }} filter multiple={true}
                  initValue={eidtData?.factors?.map(s => s.codeName) || []}
                  rules={[{ required: true, message: "请选择监测因素" }]} disabled={structId ? false : true}
                  onChange={v => {
                     setFactorChech(factorList?.filter(s => v.includes(s.proto)))
                     // setActiveKey(v)
                  }} >
                  {factorList?.map((item) => {
                     return <Form.Select.Option value={item.proto} label={item.name}></Form.Select.Option>
                  })}

               </Form.Select>

               {factorChech?.length > 0 ? <Collapse style={{ margin: '20px 0 20px 30px', width: '90%', background: '#b7c9e624' }}
                  // activeKey={activeKey}
                  keepDOM={true}
                  onChange={v => {
                     // setActiveKey(v)
                  }}
               >
                  {
                     factorChech?.map(s => {
                        return <Collapse.Panel header={s.proto + s.name} itemKey={s.proto} key={s.proto}>
                           <div style={{ background: "#FFF" }}>
                              <Form.TextArea field={s.proto + "pointDescrip"} label='布点描述' style={{ width: 400 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入布点描述" showClear
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.pointDescrip || ""}
                                 rules={[{ required: true, message: "请输入布点描述" }]}
                              />
                              <Form.Upload label="布点图片" field={s.proto + "pointPicPath"} style={{ display: 'inline-block', }}
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.pointPicPath && [{ url: `/_file-server/${eidtData?.factors?.find(c => c.codeName == s.proto)?.pointPicPath?.slice(qiniuUrl.length + 1)}`, name: eidtData?.factors?.find(c => c.codeName == s.proto)?.pointPicPath?.split('/')?.pop(), status: 'success', preview: ['png', 'jpg', 'jpeg'].includes(eidtData?.factors?.find(c => c.codeName == s.proto)?.pointPicPath?.split('.')?.pop()?.replace('.', '')) }] || null}
                                 rules={[{ required: true, message: "请上传布点图片" }]}
                                 action={`${apiRoot}/attachments/p`}
                                 accept={'.png, .jpg, .jpeg'}
                                 limit={1} maxSize={5120}
                              >
                                 <Button icon={<IconUpload />} theme="light">
                                    文件上传
                                 </Button>
                              </Form.Upload>

                              {s.proto == 2001 &&
                                 <Form.TextArea field={s.proto + "factorDescrip"} label='索力监测描述' style={{ width: 400 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入布点描述" showClear
                                    initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.factorDescrip || ""}
                                 />
                              }

                              <Form.Select label="测点选择" field={s.proto + "sensorNames"} multiple={true} placeholder="请选择测点选择" style={{ width: 300 }} showClear filter
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.sensorNames?.map(a => a.id) || []}
                                 rules={[{ required: true, message: "请选择测点选择" }]}
                              >
                                 {s.sensor?.map((item) => {
                                    return <Form.Select.Option value={item.id} label={item.name}></Form.Select.Option>
                                 })}
                              </Form.Select>
                              <Form.DatePicker field={s.proto + 'startEndTime'} label='开始结束时间' type='dateTimeRange' showClear style={{ width: 360 }}
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.startTime && [moment(eidtData?.factors?.find(c => c.codeName == s.proto)?.startTime).format('YYYY-MM-DD HH:mm:ss'), moment(eidtData?.factors?.find(c => c.codeName == s.proto)?.endTime).format('YYYY-MM-DD HH:mm:ss')] || null}
                                 rules={[{ required: true, message: "请选择开始结束时间" }]}
                              />
                              {
                                 ['2001', '4004', '4007', '4008'].includes(s.proto) &&
                                 <Form.DatePicker field={s.proto + 'initialTime'} label='数据初始时间' type='dateTime' showClear
                                    rules={[{ required: true, message: "请选择数据初始时间" }]}
                                    initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.initialTime && moment(eidtData?.factors?.find(c => c.codeName == s.proto)?.initialTime).format('YYYY-MM-DD HH:mm:ss')}
                                 />
                              }
                              {
                                 ['4009', '3001', '4004', '4001', '4007'].includes(s.proto) && <>
                                    <Form.Select label="关联温度的测点" field={s.proto + "tempName1"} showClear placeholder="请选择关联的温度测点" style={{ width: 300 }} filter
                                       initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.tempName?.find(c => c.index == 1)?.id || ""}
                                       onChange={v => {


                                       }}
                                    >
                                       {s.sensor?.map((item) => {
                                          return <Form.Select.Option value={item.id} label={item.name}></Form.Select.Option>

                                       })}
                                    </Form.Select>
                                    <Form.Select label="温度测点" field={s.proto + "tempName2"} placeholder="请选择温度测点" style={{ width: 300 }} filter showClear
                                       initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.tempName?.find(c => c.index == 2)?.id || ""}
                                    >
                                       {factorList?.find(d => d.proto == 1004 || d.proto == 1002)?.sensor?.map((item) => {
                                          return <Form.Select.Option value={item.name} label={item.name}></Form.Select.Option>

                                       })}
                                    </Form.Select>
                                    <Form.DatePicker field={s.proto + 'releTime'} label='关联开始结束时间' type='dateTimeRange' showClear style={{ width: 360 }}
                                       initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.releStartTime && [moment(eidtData?.factors?.find(c => c.codeName == s.proto)?.releStartTime).format('YYYY-MM-DD HH:mm:ss'), moment(eidtData?.factors?.find(c => c.codeName == s.proto)?.releEndTime).format('YYYY-MM-DD HH:mm:ss')] || null}
                                    />
                                 </>
                              }

                              {/* <Form.Input field={s.proto + "glStaName"} label='关联温度的测点名称' style={{ width: 300 }} placeholder="请输入关联温度的测点名称" showClear
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.glStaName || ""}
                              />
                              <Form.Input field={s.proto + "tempStaName"} label='关联温度名称' style={{ width: 300 }} placeholder="请输入关联温度名称" showClear
                                 initValue={eidtData?.factors?.find(c => c.codeName == s.proto)?.tempStaName || ""}
                              /> */}


                           </div>
                        </Collapse.Panel>
                     })
                  }


               </Collapse> : ""}

            </Form>
         </Modal >
      </>
   );
}
function mapStateToProps (state) {
   const { auth, global, members } = state;

   return {
      //   loading: members.isRequesting,
      user: auth.user,
      actions: global.actions,
      apiRoot: global.apiRoot,
      qiniuUrl: global.qiniu?.domain
   };
}

export default connect(mapStateToProps)(AutomaticModal);
