import { GroupItem } from '@/pages/Quality/Content/Info/Detail/components/AuditContent'
import Authorization from '@/components/Authorization'
import { ZhAuditBackButton, ZhButton, ZhCloseButton, ZhSubmitButton } from '@/components/Button'
import { tenderStore, userStore } from '@/store/mobx'
import { iAuditor, iLatestAuditorState } from '@/types/safe'
import { iAccountGroupItem, iUserInfo } from '@/types/setting'
import { getUserGroup } from '@/utils/common/user'
import { Button, Form, Input, message, Modal, Popover } from 'antd'
import React, { ChangeEvent, useEffect, useMemo, useState } from 'react'
import SvgIcon from '@/components/SvgIcon'
interface iAuditModalProps {
  type: 'safe' | 'quality'
  onCancel: () => void
  modalObj: {
    visible: boolean
    type: string
    loading: boolean
  }
  auditors: iAuditor[]
  onCreate: (values?: any) => void
  curAuditor: iLatestAuditorState
}
interface iModalObjState {
  searchValue: string
  visible: boolean
  auditType: string
}


const AuditModal: React.FC<iAuditModalProps> = props => {
  const [ form ] = Form.useForm()
  const { modalObj: { visible, type, loading }, onCancel, onCreate, auditors, curAuditor, type: auditType } = props


  const [ modal, setModal ] = useState<iModalObjState>({
    searchValue: '',
    visible: false,
    auditType: ''
  })
  // 当前审批人是否是审批组的最后一个审核人
  const isLastAuditor = useMemo(() => {
    if (curAuditor.progress !== '0') return false
    const len = auditors.filter(item => item.progress === '0').length
    if (len && auditors.filter(item => item.progress === '0')[len - 1].audit_id === userStore.userInfo.id) {
      return true
    }
    return false
  }, [ auditors, type, curAuditor ])
  const [ groups, setGroups ] = useState<Array<iAccountGroupItem>>([])
  const [ user, setUser ] = useState<iUserInfo>({
    account: '',
    accountGroup: 0,
    company: '',
    csrf: '',
    enable: 0,
    id: '',
    isAdmin: 0,
    mobile: '',
    name: '',
    password: '',
    position: '',
    projectId: '',
    role: '',
    telephone: ''
  })
  const comfirmBtnClick = () => {
    form.validateFields().then(values => {
      form.resetFields()
      if (user.id) {
        values.audit_id = user.id
      }

      if (type === 'pass' && isLastAuditor && curAuditor.progress === '0' && !user.id) {
        return message.error('请指定整改人')
      }
      if (type === 'back' && !user.id) {
        return message.error('请选择退回流程')
      }

      setUser({ ...user, id: '' })
      onCreate(values)
    })
  }

  useEffect(() => {
    if (visible && type === 'pass') {
      if(curAuditor.progress === '1') {
        form.setFieldsValue({ opinion: '已按要求整改完成。' })
      }

      if (isLastAuditor && auditors.findIndex(item => item.progress === '1') !== -1) {

        const auditor = auditors.find(item => item.progress === '1')
        console.log('auditor', auditor)

        auditor && (setUser({ ...user, id: auditor.audit_id, company: auditor.company, name: auditor.name, position: auditor.position }))
      }
      isLastAuditor && initGroupList()
    }
    if (visible && type === 'back') {
      if (curAuditor.progress === '1') {
        const len = auditors.filter(item => item.progress === '0').length
        const lastChecker = auditors.filter(item => item.progress === '0')[len - 1]
        setUser({ ...user, id: lastChecker.id, name: lastChecker.name })
      } else {
        const newGroup = initAuditBackGroup()
        setGroups(newGroup)
      }
    }
  }, [ visible ])
  const initGroupList = async (serach?: string) => {
    const data = await getUserGroup({ name: serach, bidsectionId: tenderStore.bid })
    setGroups(data)
  }


  const textObj = {
    start: {
      title: '提交审批',
      okText: '确认提交'
    },
    delete: {
      title: '删除巡检',
      okText: '确认删除'
    },
    close: {
      title: '审批关闭',
      okText: '确认关闭'
    },
    back: {
      title: '审批退回',
      okText: '确认退回'
    },
    pass: {
      title: curAuditor.progress === '1' ? '整改完成' : '审批通过',
      okText: curAuditor.progress === '1' ? '整改完成' : '确认通过'
    }
  }

  // 初始化审批退回下拉选择框
  const initAuditBackGroup = () => {
    const newGroup: iAccountGroupItem[] = []
    for (let index = 0; index < 3; index++) {
      if (index === 0) {
        const newAuditors = auditors
          .filter(item => item.progress === '' && item.audit_order < curAuditor.auditOrder)
          .map(item => {

            return mapUser(item.name, item.id, item.position, item.company, item.mobile)
          })
          newGroup.push({ value: '检查人', children: newAuditors })
        }
        if (index === 1) {
          const newAuditors = auditors
          .filter(item => item.progress === '0' && item.audit_order < curAuditor.auditOrder)
          .map(item => {
            return mapUser(item.name, item.id, item.position, item.company, item.mobile)
          })
        newGroup.push({ value: '审批', children: newAuditors })
      }
      if (index === 2) {
        const newAuditors = auditors
          .filter(item => item.progress === '1' && item.audit_order < curAuditor.auditOrder)
          .map(item => {
            return mapUser(item.name, item.id, item.position, item.company, item.mobile)
          })
        newGroup.push({ value: '整改', children: newAuditors })
      }

    }
    function mapUser(name: string, id: string, position: string, company: string, mobile: string) {
      return {
        account: '',
        accountGroup: 0,
        company,
        csrf: '',
        enable: 0,
        id,
        isAdmin: 0,
        mobile,
        name,
        password: '',
        position,
        projectId: '',
        role: '',
        telephone: ''
      }
    }
    return newGroup
  }

  const renderOkBtn = (type: string) => {
    if (type === 'start' || type === 'pass') {
      return (
        <ZhSubmitButton size="small" onClick={comfirmBtnClick} loading={loading}>
          {textObj[type]?.okText}
        </ZhSubmitButton>
      )
    } else if (type === 'delete') {
      return (
        <Authorization type={auditType} auth="delete">
          <Button danger size="small" onClick={comfirmBtnClick} loading={loading}>
            {textObj[type]?.okText}
          </Button>
        </Authorization>
      )
    } else if (type === 'close') {
      return (
        <Button danger size="small" onClick={comfirmBtnClick} loading={loading}>
          {textObj[type]?.okText}
        </Button>
      )
    } else if (type === 'back') {
      return (
        <ZhAuditBackButton size="small" onClick={comfirmBtnClick} loading={loading}>
          {textObj[type]?.okText}
        </ZhAuditBackButton>
      )
    }
  }

  const search = (value: string) => {
    if (value != modal.searchValue) {
      setModal({ ...modal, searchValue: value })
      initGroupList(value)
    }
  }

  const change = (e: ChangeEvent) => {
    e.persist()
    const target = e.target as HTMLTextAreaElement
    if (!target.value) {
      initGroupList()
    }
  }

  const itemSelectHandler = (item: iUserInfo, type: string = '') => {
    setUser({ ...user, ...item })
    setModal({ ...modal, visible: false, auditType: type })
  }

  const handleVisibleChange = (visible: boolean) => {
    setModal({ ...modal, visible })
  }

  const showPopover = () => {
    setModal({ ...modal, visible: true })
  }

  const handleModalCancel = () => {
    setUser({ ...user, id: '' })
    onCancel()
  }
  return (
    <Modal
      visible={visible}
      title={textObj[type]?.title}
      onCancel={handleModalCancel}
      getContainer={false}
      footer={
        <div className="pi-justify-end">
          <ZhCloseButton size="small" onClick={handleModalCancel} className="pi-mg-right-5">
            关闭
          </ZhCloseButton>
          {renderOkBtn(type)}
        </div>
      }>
      <Form form={form} layout="vertical">
        {type === 'back' ? (
          <>
            {curAuditor.progress !== '1' ? (
              <Popover
                content={groups.map(item => (
                  <GroupItem {...item} key={item.value} onSelect={(item: iUserInfo, type?: string) => itemSelectHandler(item, type)} />
                ))}
                overlayClassName="popover-card"
                trigger="click"
                visible={modal.visible}
                onVisibleChange={visible => handleVisibleChange(visible)}
                placement="bottomLeft">
                <ZhButton size="small" onClick={showPopover}>
                  <span>选择退回流程</span>
                  <SvgIcon type="xxh-caret-down" />
                </ZhButton>
              </Popover>
            ) : null}

            {user.id ? (
              <>
                <div className="pi-bordered pi-warning">
                  <span>已选择退回流程: </span>
                  <span>{user.name}</span>
                </div>
                <Form.Item name="opinion" label="审批意见">
                  <Input.TextArea rows={5} />
                </Form.Item>
              </>
            ) : null}

          </>
        ) : null}
        {type === 'delete' ? (
          <>
            <p className="mb-2">删除后，数据无法恢复，请谨慎操作。</p>
            <p className="mb-2">
              请在下方文本框输入文本「<span className="pi-red">确认删除本次巡检</span>」，以此确认删除操作。
            </p>
            <Form.Item
              name="warningText"
              rules={[
                () => ({
                  validator(rule, value) {
                    if (!value || value !== '确认删除本次巡检') {
                      return Promise.reject('请按照提示信息进行删除操作!')
                    }
                    return Promise.resolve()
                  }
                })
              ]}>
              <Input placeholder="输入文本, 确认删除" />
            </Form.Item>
          </>
        ) : null}
        {type === 'start' ? <p>请确认审批流程及信息无误。</p> : null}
        {type === 'close' ? (
          <>
            <Form.Item name="opinion" label="审批意见">
              <Input.TextArea rows={5} />
            </Form.Item>
            <p className="pi-warning">审批关闭，将直接停止该巡检流程。</p>
          </>
        ) : null}
        {type === 'pass' ? (
          <>
            <Form.Item name="opinion" label={curAuditor.progress === '1' ? '整改意见' : "审批意见"}>
              <Input.TextArea rows={5} />
            </Form.Item>
            {isLastAuditor && curAuditor.progress === '0' ? (
              <Popover
                title={<Input.Search size="small" placeholder="姓名/手机 检索" onSearch={search} onChange={e => change(e)} />}
                content={groups.map(item => (
                  <GroupItem {...item} key={item.value} onSelect={(item: iUserInfo, type?: string) => itemSelectHandler(item, type)} />
                ))}
                overlayClassName="popover-card"
                trigger="click"
                visible={modal.visible}
                onVisibleChange={visible => handleVisibleChange(visible)}
                placement="bottomLeft">
                <ZhButton size="small" onClick={showPopover}>
                  指派整改人
                </ZhButton>
              </Popover>
            ) : null}

            {user.id && isLastAuditor ? (
              <p className="pi-bordered pi-pd-8 pi-mg-top-5">
                <span>已指派整改人: </span>
                <span>
                  {user.name}-{user.position}-{user.company}
                </span>
              </p>
            ) : null}
          </>
        ) : null}
      </Form>
    </Modal>
  )
}

export default AuditModal
