import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { GoodsType } from '../SonGoodsList/data'
import { FileUpInfoType } from '../data'
import { Button, Cascader, Form, FormInstance, Input, Select } from 'antd'
import { addZiSelectChArr, cascaderChArr } from '../AddGoods'
import { API_getFileListByIds } from '@/store/action/Cledger/C4file'
import { MessageFu } from '@/utils/message'
import TextArea from 'antd/es/input/TextArea'
import { getDictFu, selectObj } from '@/utils/dataChange'
import Z3upFilesRef from '@/components/Z3upFilesRef'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'

type Props = {
  info: GoodsType
  closeFu: () => void
  succFu: (val: '新增' | '编辑', info: GoodsType) => void
  moduleId: number
  // 上传附件的信息
  fileUpInfo: FileUpInfoType
  isLook: boolean
}

function AddClues({ closeFu, succFu, moduleId, info, fileUpInfo, isLook }: Props) {
  // 获取标签 树结构
  const E1tree = useSelector((state: RootState) => state.E1tag.treeData)

  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 附件模块的ref
  const fileRef = useRef<any>(null)

  // 编辑进来获取详情
  const getInfo = useCallback(
    async (id: number) => {
      const obj: any = { ...info }

      cascaderChArr.forEach(v => {
        if (obj[v] === '0') obj[v] = null
        else if (obj[v]) {
          obj[v] = obj[v].split(',')
        }
      })

      addZiSelectChArr.forEach(v => {
        if (!obj[v]) obj[v] = null
      })

      if (obj.tagDictId) {
        const tagDictId = obj.tagDictId.split(';').map((item: string) => item.split(','))
        obj.tagDictId = tagDictId
      }

      FormBoxRef.current?.setFieldsValue(obj)

      // 设置附件
      if (obj.fileIds) {
        const fileRes = await API_getFileListByIds(obj.fileIds.split(','))
        if (fileRes.code === 0) {
          fileRef.current?.sonSetListFu(fileRes.data || [])
        }
      }
    },
    [info]
  )

  useEffect(() => {
    if (info.id > 0) getInfo(info.id)
  }, [getInfo, info.id])

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      // 获取附件
      const { list: flieList, thumb, thumbPc } = fileRef.current?.sonResListFu()

      const obj = {
        ...values,
        id: info.id > 0 ? info.id : Date.now(),
        fileIds: flieList.map((v: any) => v.id).join(','),
        thumb,
        thumbPc,
        isNew: info.id > 0 ? info.isNew : true
      }
      for (const k in obj) {
        if (obj[k] === null || obj[k] === undefined) obj[k] = ''
      }

      // 级联的数据转换成字符串
      cascaderChArr.forEach(v => {
        if (values[v]) obj[v] = values[v].join(',')
      })
      // if (1 + 1 === 2) {
      //   console.log(123, obj)
      //   return
      // }

      let tagDictId = ''
      if (obj.tagDictId.length) {
        obj.tagDictId.forEach((v: string[], i: number) => {
          tagDictId += v.join(',') + (i === obj.tagDictId.length - 1 ? '' : ';')
        })
      }

      obj.tagDictId = tagDictId

      MessageFu.success(info.id > 0 ? '编辑成功' : '新增成功')
      succFu(info.id > 0 ? '编辑' : '新增', obj)
      closeFu()
    },
    [closeFu, info.id, info.isNew, succFu]
  )

  return (
    <div className={styles.AddClues}>
      <div className='ACbox'>
        <div className='AC1'>{isLook ? '线索查看' : info.id > 0 ? '线索编辑' : '线索新增'}</div>

        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <div className='ACmain'>
            <Form.Item
              label='线索名称'
              name='name'
              rules={[{ required: true, message: '请输入' }]}
              getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
            >
              <Input readOnly={isLook} placeholder='请输入' showCount maxLength={30} />
            </Form.Item>

            <Form.Item
              label='线索编号'
              name='num'
              getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
            >
              <Input
                readOnly={isLook}
                placeholder={isLook ? '（空）' : '请输入'}
                showCount
                maxLength={30}
              />
            </Form.Item>

            <Form.Item label='联系方式' name='phone'>
              <Input
                readOnly={isLook}
                placeholder={isLook ? '（空）' : '请输入'}
                showCount
                maxLength={30}
              />
            </Form.Item>

            <Form.Item label='完残程度' name='tornLevel'>
              <Select
                disabled={isLook}
                allowClear={true}
                placeholder={isLook ? '（空）' : '请输入'}
                options={selectObj['完残程度']}
              />
            </Form.Item>
            <Form.Item label='初步藏品标签' name='tagDictId'>
              <Cascader
                disabled={isLook}
                changeOnSelect
                options={E1tree}
                placeholder={isLook ? '（空）' : '请选择'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
                multiple
                maxTagCount='responsive'
              />
            </Form.Item>

            <Form.Item label='初步藏品年代' name='ageDictId'>
              <Cascader
                disabled={isLook}
                changeOnSelect
                options={getDictFu('藏品年代')}
                placeholder={isLook ? '（空）' : '请输入'}
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
              />
            </Form.Item>

            <Form.Item label='线索简介' name='intro' className='ant-form-itemFull'>
              <TextArea
                readOnly={isLook}
                placeholder={isLook ? '（空）' : '请输入'}
                showCount
                maxLength={500}
              />
            </Form.Item>

            <Form.Item label='线索意向' name='intention' className='ant-form-itemFull'>
              <TextArea
                readOnly={isLook}
                placeholder={isLook ? '（空）' : '请输入'}
                showCount
                maxLength={500}
              />
            </Form.Item>

            <Form.Item label='备注' name='remark' className='ant-form-itemFull'>
              <TextArea
                readOnly={isLook}
                placeholder={isLook ? '（空）' : '请输入'}
                showCount
                maxLength={500}
              />
            </Form.Item>

            {/* 附件 */}
            <div className='ACfull'>
              <div className='ACfullll'>附件：</div>
              <div className='ACfullrr'>
                <Z3upFilesRef
                  oneIsCover={true}
                  ref={fileRef}
                  isLook={isLook}
                  moduleId={moduleId}
                  {...fileUpInfo}
                />
              </div>
            </div>

            {/* 确定和取消按钮 */}
            <Form.Item className='ACbtnok'>
              {isLook ? (
                <Button onClick={closeFu}>关闭</Button>
              ) : (
                <>
                  <Button type='primary' htmlType='submit'>
                    提交
                  </Button>
                  <MyPopconfirm txtK='取消' onConfirm={closeFu} />
                </>
              )}
            </Form.Item>
          </div>
        </Form>
      </div>
    </div>
  )
}

const MemoAddClues = React.memo(AddClues)

export default MemoAddClues
