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 [structChech, setStructChech] = useState([]);     //选中的结构物
   const [factorChech, setFactorChech] = useState({});     //选中的结构物
   const [activeKey, setActiveKey] = useState([]);     //
   const [correlationId, setCorrelationId] = useState([]);     //


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

         let data = await getData(eidtData?.projectId)
         let struc = data?.filter(s => eidtData?.structId?.includes(s.strucId)) || []

         setStructChech(struc)
         let Factor = {}
         struc?.forEach(d => {
            Factor[d.strucId] = d.factor?.filter(w => eidtData?.structList?.find(h => h.structId == d.strucId)?.factors?.map(g => g.codeName)?.includes(w.proto))
         })
         setFactorChech(Factor)
         // 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) => {
                  console.log(11, v);
                  let data = {
                     id: eidtData?.id,
                     reportName: v.reportName,   //报表名称
                     projectId: v.projectId,    //所属项目
                     projectName: v.projectName,    //项目名称
                     reportType: v.reportType,  //报表类型
                     reportPicPath: v.reportPicPath && v.reportPicPath[0] && v.reportPicPath[0]?.response?.url || eidtData.reportPicPath,  //首页图片
                     framer: v.framer,   //制定者
                     auditor: v.auditor,  //审核者
                     ratifier: v.ratifier,   //批准者
                     coverTime: v.coverTime && moment(v.coverTime).format('YYYY-MM-DD'),
                     structId: v.structId,    //结构物id
                     structList: []
                  }

                  v.structId?.forEach(p => {
                     let structFind = eidtData?.structList?.find(d => d.structId == p) || {}
                     let structData = { structId: p }
                     let structNameIndex = p.toString().length || 0
            
                     for (let key in v) {
                        if (key?.indexOf(p) != -1) {
                           //结构物概况图片
                           if (key?.slice(structNameIndex) == 'overview') structData.overview = v[key] && v[key][0]?.response?.url || structFind.overview
                           //结构物描述
                           if (key?.slice(structNameIndex) == 'projectOverview') structData.projectOverview = v[key]
                           //结论
                           if (key?.slice(structNameIndex) == 'conclusion') structData.conclusion = v[key]
                           //开始结束时间
                           if (key?.slice(structNameIndex) == 'reportTime') {
                              structData.reportStartTime = v[key] && v[key][0] && moment(v[key][0]).format('YYYY-MM-DD HH:mm:ss')
                              structData.reportEndTime = v[key] && v[key][1] && moment(v[key][1]).format('YYYY-MM-DD HH:mm:ss')
                           }
                           //包含的监测因素
                           structData.factors = []
                        }
                     }

                     // debugger

                     v[p + 'factorId']?.forEach(d => {
                        let factorFind = structFind?.factors?.find(c => c.codeName == d) || {}
                        let index = d.length + structNameIndex + 5
                        let factorData = {}
                        for (let key in v) {
                           factorData.codeName = d
                           factorData.tempName = factorData.tempName || []
                           if (key?.indexOf(p + 'struc') != -1 && key?.indexOf('struc' + 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 ||
                                 factorFind.pointPicPath
                              //索力监测描述
                              if (key?.slice(index) == 'factorDescrip') factorData.factorDescrip = v[key]
                              //测点选择
                              if (key?.slice(index) == 'sensorNames') factorData.sensorNames = factorChech[p]?.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] && v[key][0] && moment(v[key][0]).format('YYYY-MM-DD HH:mm:ss')
                                 factorData.endTime = v[key] && v[key][1] && 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[p]?.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[p]?.find(p => p.proto == 1004)?.sensor?.find(f => v[key] == f.id)?.name
                                 })
                              }
                              //数据初始时间
                              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] && v[key][0] && moment(v[key][0]).format('YYYY-MM-DD HH:mm:ss')
                                 factorData.releEndTime = v[key] && v[key][1] && 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
                        structData.factors?.push(factorData)
                     })

                     data.structList.push(structData)
                  })

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

               })
            }}
            width={770}
            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', [])
                     setStructId([])
                     // setFactorList([])
                     // form.current.setValue('factorId', [])
                     setStructChech([])
                  }} >
                  {projectList?.map((item) => {
                     return <Form.Select.Option value={item.id} key={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: "请输入项目名称" }]}
               />
               <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.DatePicker label="封面时间" field="coverTime" showClear style={{ width: 300 }}
                  initValue={eidtData?.coverTime && moment(eidtData?.coverTime).format('YYYY-MM-DD') || ""}
               />

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

                  })}
               </Form.Select>

               {/*所选结构物 */}
               {structChech?.length > 0 ? <Collapse style={{ margin: '20px 0 20px 30px', width: '90%', background: '#b7c9e624' }}
                  // activeKey={activeKey}
                  keepDOM={true}
                  onChange={v => {
                     // setActiveKey(v)
                  }}
               >
                  {
                     structChech?.map(s => {
                        let structFind = eidtData?.structList?.find(d => d.structId == s.strucId) || {}
                        return <Collapse.Panel header={s.strucName} itemKey={`'${s.strucId}'`} key={s.strucId}>
                           <div style={{ background: "#FFF" }}>
                              <Form.Upload label="结构物概况图片" field={s.strucId + "overview"} style={{ display: 'inline-block', }}
                                 initValue={structFind?.overview && [{ url: `/_file-server/${structFind?.overview?.slice(qiniuUrl.length + 1)}`, name: structFind.overview?.split('/')?.pop(), status: 'success', preview: ['png', 'jpg', 'jpeg'].includes(structFind.overview?.split('.')?.pop()?.replace('.', '')) }] || null}
                                 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.TextArea field={s.strucId + "projectOverview"} label='结构物描述' style={{ width: 390 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入结构物描述" showClear
                                 initValue={structFind?.projectOverview || ""}
                                 rules={[{ required: true, message: "请输入结构物描述" }]}
                              />
                              <Form.TextArea field={s.strucId + "conclusion"} label='结论' style={{ width: 390 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入结论" showClear
                                 initValue={eidtData?.structList?.find(d => d.structId == s.strucId)?.conclusion || ""}
                                 rules={[{ required: true, message: "请输入结构物描述" }]}
                              />
                              <Form.DatePicker field={s.strucId + 'reportTime'} label='开始结束时间' type='dateTimeRange' showClear
                                 initValue={structFind?.reportStartTime && [moment(structFind?.reportStartTime).format('YYYY-MM-DD HH:mm:ss'), moment(structFind?.reportEndTime).format('YYYY-MM-DD HH:mm:ss')] || null} style={{ width: 390 }}
                                 rules={[{ required: true, message: "请选择开始结束时间" }]}
                              />
                              <Form.Select label="包含的监测因素" field={s.strucId + "factorId"} placeholder="请选择监测因素" showClear style={{ width: 300 }} filter multiple={true}
                                 initValue={structFind?.factors?.map(s => s.codeName) || []}
                                 rules={[{ required: true, message: "请选择监测因素" }]} disabled={structId ? false : true}
                                 onChange={v => {
                                    setFactorChech({ ...factorChech, [s.strucId]: s.factor?.filter(d => v.includes(d.proto)) || [] })
                                    // setActiveKey(v)
                                 }} >
                                 {s.factor?.map((item) => {
                                    return <Form.Select.Option value={item.proto} key={item.proto} label={item.name}></Form.Select.Option>
                                 })}

                              </Form.Select>
                              {factorChech[s.strucId] ? <Collapse style={{ margin: '20px 0 20px 30px', width: '90%', background: '#b7c9e624' }}
                                 // activeKey={activeKey}
                                 keepDOM={true}
                                 onChange={v => {
                                    // setActiveKey(v)
                                 }}
                              >
                                 {
                                    factorChech[s.strucId]?.map(p => {
                                       let factorFind = structFind?.factors?.find(c => c.codeName == p.proto) || {}
                                       return <Collapse.Panel header={p.name} itemKey={p.proto} key={p.proto}>
                                          <div style={{ background: "#FFF" }}>
                                             <Form.TextArea field={s.strucId + 'struc' + p.proto + "pointDescrip"} label='布点描述' style={{ width: 400 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入布点描述" showClear
                                                initValue={factorFind?.pointDescrip || ""}
                                                rules={[{ required: true, message: "请输入布点描述" }]}
                                             />
                                             <Form.Upload label="布点图片" field={s.strucId + 'struc' + p.proto + "pointPicPath"} style={{ display: 'inline-block', }}
                                                initValue={factorFind?.pointPicPath && [{ url: `/_file-server/${factorFind?.pointPicPath?.slice(qiniuUrl.length + 1)}`, name: factorFind?.pointPicPath?.split('/')?.pop(), status: 'success', preview: ['png', 'jpg', 'jpeg'].includes(factorFind?.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.strucId + 'struc' + p.proto + "factorDescrip"} label='索力监测描述' style={{ width: 400 }} autosize={{ minRows: 2, maxRows: 10 }} placeholder="请输入布点描述" showClear
                                                   initValue={factorFind?.factorDescrip || ""}
                                                />
                                             }

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


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

                                                      })}
                                                   </Form.Select>
                                                   <Form.Select label="温度测点" field={s.strucId + 'struc' + p.proto + "tempName2"} placeholder="请选择温度测点" style={{ width: 300 }} filter showClear
                                                      initValue={factorFind?.tempName?.find(c => c.index == 2)?.id || ""}
                                                   >
                                                      {s.factors?.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.strucId + 'struc' + p.proto + 'releTime'} label='关联开始结束时间' type='dateTimeRange' showClear style={{ width: 360 }}
                                                      initValue={factorFind?.releStartTime && [moment(factorFind?.releStartTime).format('YYYY-MM-DD HH:mm:ss'), moment(factorFind?.releEndTime).format('YYYY-MM-DD HH:mm:ss')] || null}
                                                   />
                                                </>
                                             }
                                          </div>
                                       </Collapse.Panel>
                                    })
                                 }


                              </Collapse> : ""}
                           </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);
