import React, {useState} from 'react';
import { useModel, useRequest } from 'umi';
import { Card, Form, Button, Drawer, Modal, message } from 'antd';
import classNames from "classnames";
import utilsStyles from '@/utils/utils.less';
import Step from '../components/Step';
import _ from "lodash";
import moment from "moment";
import style from "../index.less";
import ShiftsForm from './componentrs/ShiftsForm'

import {fetchShiftsAudit, fetchShiftsInfo} from '@/services/staff'

const isLargeScreen = document.body.clientWidth >= 1920;
const {confirm} = Modal

const WorkInfo = (props) => {
  const {
    match: { params },
  } = props;

  const {initialState} = useModel('@@initialState')
  const currentUser = initialState?.currentUser || {}

  const {id, isAudit} = params;
  const requestType = isAudit && isAudit === 'audit' ? '2' : '1'

  const [visible, setVisible] = useState(false);
  const [remark, setRemark] = useState();
  const [disabled, setDisabled] = useState(false);
  const [isLast, setIsLast] = useState(false)

  /**
   * @表单提交
   */
  const [form] = Form.useForm();

  const leaveInfo = useRequest(() => fetchShiftsInfo(id), {
    onSuccess: res => {
      res.enclosurs = res?.enclosurs?.map((item, index) => ({
        name: item.enclosurName, status: 'done', url: item.enclosurUrl
      })) || []
      res.timeBOS = res?.adjustmentTime?.map((item) => ({
        aadjustmentTime: moment(item.aAdjustmentTime),
        badjustmentTime: moment(item.bAdjustmentTime)
      }))
      res.personBOS = {
        auserId: res?.auserId,
        auserName: res?.auserName,
        buserId: res?.buserId,
        buserName: res?.buserName,
      }
      res.adjustmentType = `${res?.adjustmentType || ''}`


      const userList = res?.adb?.approvedBy;
      const userInfo = userList.findIndex(item => item.userId === currentUser.id);
      setIsLast(userInfo === userList?.length -1)
      const result = userList[userInfo].auditState === 2 || res?.adb?.auditState === 3;
      setDisabled(result)
      form.setFieldsValue(res)
    }
  });
  const leaveAudit = useRequest(fetchShiftsAudit, {
    manual: true,
    onSuccess: (res) => {
      if (res) {
        closeCurrentPage('/ops/staff/shifts')
      } else {
        message.error('审批失败!')
      }
    }
  })

  const closeDrawer = () => {
    setVisible(false)
  }

  const handleSubmit = (payload) => {
    leaveAudit.run(payload)
  }


  const confirmSubmit = (payload) => {
    confirm({
      centered: true,
      title: '审批询问',
      icon: null,
      content: '是否结束审批流程,无需提交上级审批?',
      okText: '是',
      cancelText: '否',
      onOk() {
        payload.auditInquiry = true
        handleSubmit(payload)
      },
      onCancel() {
        payload.auditInquiry = false
        handleSubmit(payload)
      }
    });
  }
  const auditAction = (auditState) => {
    const payload = {id, auditState, remarks: remark || ''}
    if (auditState === 2) {
      if (!isLast && leaveInfo?.data?.adb?.auditInquiry){
        confirmSubmit(payload);
        return
      }
      confirm({
        centered: true,
        title: '审批询问',
        icon: null,
        content: '是否通过该排班?',
        okText: '是',
        cancelText: '否',
        onOk() {
          handleSubmit(payload)
        },
      });
    }
    if (auditState === 3) {
      handleSubmit(payload)
    }
  }
  /**
   * @页面数据
   */


  const titleClassName =
    {1: "btn_warning", 2: "btn_success", 3: "btn_fail"}[leaveInfo?.data?.adb?.auditState]

  return (
    <div className={ classNames(utilsStyles.disFlexCol, utilsStyles.fullContainer) }>
      <div className={style.wrap_page}>
        <Card bodyStyle={{padding: 0}} loading={leaveInfo?.loading || false} className={isLargeScreen ? style.work_info_readonly_left : ''}>
          <Form requiredMark={false} style={{flex: 1, height: '100%'}} form={form}>
            <ShiftsForm level={leaveInfo?.data?.adjustmentType} form={form} disabled={true} type="info"/>
          </Form>
        </Card>
        {isLargeScreen ? (
          <div className={style.work_item_right}>
            <Card loading={leaveInfo?.loading || leaveAudit?.loading || false}  size="small" title="审批信息" extra={
              <div className={titleClassName}>
                {{1: '待审核', 2: '已审批', 3: '已驳回', 4: '审核中'}[leaveInfo?.data?.adb?.auditState]}
              </div>
            } style={{width: '100%'}}>
              <Step
                createInfo={{
                  creationTime: leaveInfo?.data?.creationTime,
                  creationName: leaveInfo?.data?.applicantName,
                  creationUrl: leaveInfo?.data?.applicantUrl,
                }}
                userId={currentUser.id}
                disabled={disabled}
                requestType={requestType}
                stepList={leaveInfo?.data?.adb?.approvedBy || []}
                onEdit={setRemark}
                onPass={() => auditAction(2)}
                onRefuse={() => auditAction(3)}
              />
            </Card>
          </div>
        ) : (
          <div className={style.fixed_bottom_box}>
            <Button
              onClick={() => setVisible(true)}
              className={style.bottom_btn}
            >审批详情</Button>
          </div>
        )}

        <Drawer
          width={300}
          bodyStyle={{padding: 0}}
          placement="right"
          closable={false}
          onClose={closeDrawer}
          visible={visible}
        >
          <div className={classNames(style.drawer_tittle, 'pos_btw')}>
            <span>审批信息</span>
            <div className={titleClassName}>
              {{1: '待审核', 2: '已审批', 3: '已驳回', 4: '审核中'}[leaveInfo?.data?.adb?.auditState]}
            </div>
          </div>
          <div style={{padding: '0 20px'}}>
            <Step
              createInfo={{
                creationTime: leaveInfo?.data?.creationTime,
                creationName: leaveInfo?.data?.applicantName,
                creationUrl: leaveInfo?.data?.applicantUrl,
              }}
              userId={currentUser.id}
              disabled={disabled}
              requestType={requestType}
              stepList={leaveInfo?.data?.adb?.approvedBy || []}
              onEdit={setRemark}
              onPass={() => auditAction(2)}
              onRefuse={() => auditAction(3)}
            />
          </div>

        </Drawer>

      </div>
    </div>
  );
};

export default WorkInfo