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

// 级联的数据转换成字符串
export const cascaderChArr = ['ageDictId', 'pcsUnitDictId', 'textureDictId', 'qualityLevelDictId']

// 下拉框为空的时候转变成null
export const addZiSelectChArr = [
  'level',
  'tornLevel',
  'keep',
  'qualityScope',
  'qualityUnitDictId',
  'inGoodYearScope',
  'source'
]

type Props = {
  info: GoodsType
  closeFu: () => void
  isEdit: boolean //藏品编辑-模块
  editSnap?: GoodsType //藏品模块属于新增还是编辑
  succFu: (val: '新增' | '编辑', info: GoodsType, oldInfo?: GoodsType, keyArr?: string[]) => void
  moduleId: number
  // 上传附件的信息
  fileUpInfo: FileUpInfoType
  APIsave: any
}

function AddGoods({
  closeFu,
  succFu,
  isEdit,
  moduleId,
  info,
  APIsave,
  fileUpInfo,
  editSnap
}: Props) {
  // 获取标签 树结构
  const E1tree = useSelector((state: RootState) => state.E1tag.treeData)
  const E3tree = useSelector((state: RootState) => state.E3label.treeData)

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

  // 故事模块的ref
  const guShiRef = useRef<any>(null)

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

  // 藏品编辑模块用来对比
  const objOld = useRef<any>({})

  const resInfoFu = useCallback(
    async (infoRes: GoodsType) => {
      // 藏品编辑信息保存
      objOld.current = { ...infoRes }

      const obj: any = editSnap && editSnap.id ? { ...editSnap } : { ...infoRes }
      // makeDate inGoodYear 2个日期需要格式处理一下
      if (obj.makeDate) obj.makeDate = dayjs(obj.makeDate)
      if (obj.inGoodYear) obj.inGoodYear = dayjs(obj.inGoodYear)

      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.artDictId) {
        const artDictId = obj.artDictId.split(';').map((item: string) => item.split(','))
        obj.artDictId = artDictId
      }
      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 || [])
        }
      }
    },
    [editSnap]
  )

  // 编辑进来获取详情
  const getInfo = useCallback(
    async (id: number) => {
      if (info.pageType === 'clue') {
        // 从征集进来 不用拿详情
        resInfoFu(info)
      } else {
        const res = await API_getGoodsInfo(id)
        if (res.code === 0) resInfoFu(res.data)
      }
    },
    [info, resInfoFu]
  )

  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()
      // 获取故事
      let guShiList: any[] = []
      let delIds: any[] = []
      if (guShiRef.current) {
        const gushiInfo = guShiRef.current?.getGuShiListBySon()
        guShiList = gushiInfo.guShiList
        delIds = gushiInfo.delIds
      }
      // 2个日期的格式处理
      let makeDate = ''
      if (values.makeDate) makeDate = dayjs(values.makeDate).format('YYYY-MM-DD')
      let inGoodYear = ''
      if (values.inGoodYear) inGoodYear = dayjs(values.inGoodYear).format('YYYY')

      const obj = {
        ...values,
        id: info.pageType === 'clue' ? null : info.id > 0 ? info.id : null,
        makeDate,
        inGoodYear,
        fileIds: flieList.map((v: any) => v.id).join(','),
        thumb,
        thumbPc,
        delStoryIds: delIds.length ? delIds : null,
        storyIds: guShiList.map((v: any) => v.id).join(',')
      }
      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(',')
      })

      // 文创标签-级联多选特殊处理
      let artDictId = ''
      if (obj.artDictId.length) {
        obj.artDictId.forEach((v: string[], i: number) => {
          artDictId += v.join(',') + (i === obj.artDictId.length - 1 ? '' : ';')
        })
      }

      obj.artDictId = artDictId

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

      obj.tagDictId = tagDictId

      if (isEdit) {
        // 藏品编辑模块
        let flag = true
        const oldInfoObj = { ...objOld.current }
        if (oldInfoObj.makeDate)
          oldInfoObj.makeDate = dayjs(oldInfoObj.makeDate).format('YYYY-MM-DD')
        if (oldInfoObj.inGoodYear)
          oldInfoObj.inGoodYear = dayjs(oldInfoObj.inGoodYear).format('YYYY')

        const keyArr: string[] = []

        for (const k in obj) {
          if (!['delStoryIds', 'storyIds', 'fileIds'].includes(k)) {
            if ((oldInfoObj[k] || obj[k]) && oldInfoObj[k] !== obj[k]) {
              keyArr.push(k)
              flag = false
            }
          }
        }

        const oldFileIds = (oldInfoObj.fileIds || '')
          .split(',')
          .map((c: any) => Number(c))
          .sort((a: any, b: any) => b - a)
          .join(',')
        const newFileIds = (obj.fileIds || '')
          .split(',')
          .map((c: any) => Number(c))
          .sort((a: any, b: any) => b - a)
          .join(',')
        if (oldFileIds !== newFileIds) {
          flag = false
          keyArr.push('fileIds')
        }

        // if (1 + 1 === 2) {
        //   console.log('---------', keyArr, oldInfoObj, obj)
        //   return
        // }

        if (flag) return MessageFu.warning('未修改藏品信息')

        succFu(editSnap ? '编辑' : '新增', obj, oldInfoObj, keyArr)
      } else {
        const res = await APIsave(obj)
        if (res.code === 0) {
          MessageFu.success(info.id > 0 ? '编辑成功' : '新增成功')
          // if (1 + 1 === 2) {
          //   console.log('----------------', info)
          //   return
          // }

          const resObj = { ...res.data }
          if (info.pageType === 'clue') {
            resObj.clueId = info.id
          }

          succFu(info.id > 0 ? '编辑' : '新增', resObj)
          closeFu()
        }
      }
    },
    [APIsave, closeFu, editSnap, info.id, info.pageType, isEdit, succFu]
  )

  return (
    <div className={styles.AddGoods}>
      <div className='AGbox'>
        <div className='AG1'>
          {isEdit
            ? `藏品修改${editSnap ? '- 编辑' : '- 新增'}`
            : info.id > 0
              ? '藏品编辑'
              : '藏品新增'}
        </div>

        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          initialValues={{
            makeDate: dayjs(),
            makeUser: getTokenInfo().user.realName,
            inGoodYear: dayjs()
          }}
        >
          <div className='AGmain'>
            <Form.Item
              label='藏品登记号'
              name='num'
              rules={[{ required: true, message: '请输入' }]}
              getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
            >
              <Input placeholder='请输入' showCount maxLength={30} />
            </Form.Item>

            <Form.Item label='文创标签' name='artDictId'>
              <Cascader
                changeOnSelect
                options={E3tree}
                placeholder='请选择'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
                multiple
                maxTagCount='responsive'
              />
            </Form.Item>

            <Form.Item
              label='制档日期'
              name='makeDate'
              rules={[{ required: true, message: '请选择' }]}
            >
              <DatePicker
                allowClear={false}
                disabledDate={current => current && current > dayjs().endOf('day')}
              />
            </Form.Item>

            <Form.Item
              label='制档人'
              name='makeUser'
              rules={[{ required: true, message: '请输入' }]}
              getValueFromEvent={e => e.target.value.trim()}
            >
              <Input placeholder='请输入' showCount maxLength={30} />
            </Form.Item>

            {/* 横线 */}
            <div className='AGxian'></div>

            <Form.Item
              label='藏品名称'
              name='name'
              rules={[{ required: true, message: '请输入' }]}
              getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
            >
              <Input placeholder='请输入' showCount maxLength={30} />
            </Form.Item>

            <Form.Item label='藏品原名' name='oldName'>
              <Input placeholder='请输入' showCount maxLength={30} />
            </Form.Item>

            <Form.Item label='藏品级别' name='level'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['藏品级别']} />
            </Form.Item>

            <Form.Item label='藏品标签' name='tagDictId'>
              <Cascader
                changeOnSelect
                options={E1tree}
                placeholder='请选择'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
                multiple
                maxTagCount='responsive'
              />
            </Form.Item>

            <Form.Item label='藏品年代' name='ageDictId'>
              <Cascader
                changeOnSelect
                options={getDictFu('藏品年代')}
                placeholder='请选择'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
              />
            </Form.Item>

            <Form.Item label='具体年代' name='ageInfo'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>

            <div className='AGrow'>
              <Form.Item
                className='AGrow1'
                label='实际数量'
                name='pcs'
                rules={[{ required: true, message: '请输入' }]}
              >
                <InputNumber min={1} max={99999999} precision={0} placeholder='请输入正整数' />
              </Form.Item>
              <Form.Item
                className='AGrow2'
                name='pcsUnitDictId'
                rules={[{ required: true, message: '请选择' }]}
              >
                <Cascader
                  changeOnSelect
                  options={getDictFu('数量单位')}
                  placeholder='请选择'
                  fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                  allowClear={true}
                  showSearch={true}
                />
              </Form.Item>
            </div>

            <Form.Item label='质地' name='textureDictId'>
              <Cascader
                changeOnSelect
                options={getDictFu('质地')}
                placeholder='请选择'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
              />
            </Form.Item>

            <Form.Item label='完残程度' name='tornLevel'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['完残程度']} />
            </Form.Item>

            <Form.Item label='完残状况' name='tornInfo'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>

            <Form.Item label='保存状态' name='keep'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['保存状态']} />
            </Form.Item>

            <Form.Item label='保护修复情况' name='keepInfo'>
              <TextArea placeholder='请输入' showCount maxLength={500} />
            </Form.Item>

            <div className='AGrowSize'>
              <div className='AGrowSizeTxt'>
                通长、通宽、通高 - 请填入非负数字，最多三位小数，单位cm
              </div>

              <Form.Item label='尺寸' name='sizeL'>
                <InputNumber min={0} max={99999999} precision={3} placeholder='通长' />
              </Form.Item>

              <Form.Item name='sizeW'>
                <InputNumber min={0} max={99999999} precision={3} placeholder='通宽' />
              </Form.Item>
              <Form.Item name='sizeH'>
                <InputNumber min={0} max={99999999} precision={3} placeholder='通高' />
              </Form.Item>
            </div>

            <Form.Item label='具体尺寸' name='sizeInfo'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>

            <Form.Item label='质量范围' name='qualityScope'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['质量范围']} />
            </Form.Item>

            <div className='AGrow'>
              <Form.Item className='AGrow1' label='具体质量' name='quality'>
                <InputNumber min={0} max={99999999} precision={3} placeholder='请输入非负数字' />
              </Form.Item>
              <Form.Item className='AGrow2' name='qualityUnitDictId'>
                <Select allowClear={true} placeholder='请选择' options={selectObj['质量单位']} />
              </Form.Item>
            </div>

            <Form.Item label='入藏年度' name='inGoodYear'>
              <DatePicker
                picker='year'
                disabledDate={current => current && current > dayjs().endOf('year')}
              />
            </Form.Item>

            <Form.Item label='入藏时间范围' name='inGoodYearScope'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['入藏时间范围']} />
            </Form.Item>

            <Form.Item label='文物来源' name='source'>
              <Select allowClear={true} placeholder='请选择' options={selectObj['文物来源']} />
            </Form.Item>

            <Form.Item label='产地' name='born'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>

            <Form.Item label='质量等级' name='qualityLevelDictId'>
              <Cascader
                changeOnSelect
                options={getDictFu('质量等级')}
                placeholder='请选择'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                showSearch={true}
              />
            </Form.Item>

            <Form.Item label='著者' name='pressAuthor'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>
            <Form.Item label='版本' name='pressVersion'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>
            <Form.Item label='存卷' name='pressFile'>
              <Input placeholder='请输入' showCount maxLength={50} />
            </Form.Item>
            <Form.Item label='藏品简介' name='intro'>
              <TextArea placeholder='请输入' showCount maxLength={2000} />
            </Form.Item>
            <Form.Item label='备注' name='remark'>
              <TextArea placeholder='请输入' showCount maxLength={500} />
            </Form.Item>

            {/* 横线 */}
            <div className='AGxian'></div>

            {/* 附件 */}
            <div className='AGfull'>
              <div className='AGfullll'>附件：</div>
              <div className='AGfullrr'>
                <Z3upFilesRef ref={fileRef} oneIsCover={true} moduleId={moduleId} {...fileUpInfo} />
              </div>
            </div>
            {/* 横线 */}
            {isEdit ? null : (
              <>
                <div className='AGxian'></div>
                <div className='AGfull'>
                  <div className='AGfullll'>故事：</div>
                  <div className='AGfullrr'>
                    <GuShi moduleId={moduleId} ref={guShiRef} goodsId={info.id} />
                  </div>
                </div>
              </>
            )}

            {/* 确定和取消按钮 */}
            <Form.Item className='AGbtnok'>
              <Button type='primary' htmlType='submit'>
                提交
              </Button>
              <MyPopconfirm txtK='取消' onConfirm={closeFu} />
            </Form.Item>
          </div>
        </Form>
      </div>
    </div>
  )
}

const MemoAddGoods = React.memo(AddGoods)

export default MemoAddGoods
