/* eslint-disable */
import React, { Component } from 'react';
import moment from 'moment';
import { Input, Layout, Steps, Select, Button, Modal,message, Spin } from 'antd-v4';
import { UserOutlined } from '@ant-design/icons';
import * as commonUtils from '@/utils/utils';/* 通用方法 */
import * as commonServices from '@/services/services';/*   服务类   */
import commonConfig from '../../../utils/config';
import flowPicture2 from '@/assets/flow/flowpic.png';
import styles from './index.less';
import AntdDraggableModal from "../AntdDraggableModal";
import {value} from "lodash/seq";


const { Content } = Layout;
const { TextArea } = Input;
class CommonExamInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      flowLoading: false,
    };
  }
  /* 同意/驳回 */
  submitHandler = async (btnName ) => {
    const { app } = this.props;
    const { textareaValue } = this.state;
    const { currentPane, panes, userinfo } = app;
    const sFlowData = currentPane?.sFlowData; /* 业务流完整数据源 */
    let sFlowObj = {};
    if (commonUtils.isNotEmptyObject(sFlowData)) {
      const sFlowArr = [JSON.parse(sFlowData.toString())];
      if (commonUtils.isNotEmptyArr(sFlowArr)) {
        sFlowObj = sFlowArr[0];
      }
    }
    const historyList = sFlowObj?.historyList; /* 审批流程 */
    const dataList = sFlowObj?.dataList; /* 数据集 */
    const sBrandsId = userinfo?.sBrandsId;
    const sSubsidiaryId = userinfo?.sSubsidiaryId;
    const sUserId = userinfo?.sUserName;
    const taskId = sFlowObj?.taskId;
    const sTaskId = sFlowObj?.taskId;
    // const commentObj = document.getElementById('comment');
    // const comment = commentObj?.value ; /* 驳回理由 */
    if(btnName ==='reject' && commonUtils.isEmptyObject(textareaValue)){
      message.warn("请输入驳回理由!")
      return;
    }
    // 如果是同意按钮，设置loading状态并开始进度计
    this.setState({
      flowLoading: true,
      progressCount: 0
    });

    // 模拟进度计数直到101
    const progressInterval = setInterval(() => {
      this.setState(prevState => {
        const newCount = prevState.progressCount + 1;
        if (newCount > 101) {
          clearInterval(progressInterval);
          return { progressCount: 101 };
        }
        return { progressCount: newCount };
      });
    }, 50); // 每50ms增加1，大约5秒到101
    const bizFlowVo =  sFlowObj.bizFlowVo;
    const sTableParamsValue= sFlowObj.bizFlowVo?.sTableParamsValue;
    const sFormData= commonUtils.isNotEmptyObject(sTableParamsValue) ? JSON.parse(sTableParamsValue) : {};
    /* 可输入文本 */
    const dataDynamicList = commonUtils.isNotEmptyArr(dataList) ? dataList.filter(item  =>  item.name !=='sEmployeeName') : [];
    if(commonUtils.isNotEmptyArr(dataDynamicList)) {
      for (const child of dataDynamicList) {
        const name = child.name;
        const bEdit = !child.bEdit; /* 是否编辑 */
        const type= child.type; /* 文本类型 */
        const obj = {};
        if( bEdit ) { /* 可编辑的都传入 */
          const sRealName =  name +'_sRealName';
          const sValue = this.state[name];
          if (btnName === 'agree' && commonUtils.isEmptyObject(sValue)) {
            message.warn(`${child.title} 为必填项！`);
            // 如果是同意按钮，清除loading状态
            this.setState({ flowLoading: false });
            return;
          }
          sFormData[name]= sValue;
          if(child.bSelect) { /* 下拉需要传sRealName */
            sFormData[sRealName]=  this.state[sRealName];
          }

        }
      }
    }

    const prefix =  commonConfig.server_host + "currencyFlow";
    let url = prefix + "/complete/" + taskId+"/"+sBrandsId+"/"+sSubsidiaryId+"/"+sUserId;
    // const data = $('#form-leave-edit').serialize();
    const data = sFormData;
    if(btnName === 'agree'){
      data.approved = true;
    }else if(btnName ==='reject') {
      data.approved = false;
    }
    data.id = bizFlowVo?.id;
    data.taskId = taskId;
    data.sTaskId = sTaskId;
    data.sSrcId = bizFlowVo?.sSrcId;
    data.sSrcFormId = bizFlowVo?.sSrcFormId;
    data.sUserId = sUserId;
    data.sUserName = sUserId;
    data.messagesTitle = bizFlowVo?.title;
    data.selectMap = {};
    data.comment = textareaValue;
    const { token }= this.props;

    // console.log('接口开始执行，等待1分钟...');
    // await new Promise(resolve => setTimeout(resolve, 10000));
    // console.log('1分钟等待结束，开始处理请求');
    const sReturn = (await commonServices.postValueService(token, data, url)).data;
    if(commonUtils.isNotEmptyObject(sReturn)) {
      if (sReturn.code > 0 || sReturn.code === 0) {
        message.success('操作成功！');
        /* 找到当前登陆人 把登录人的状态更新为已同意 或是已驳回 */
        // const userIndex = commonUtils.isNotEmptyArr(historyList) ? historyList.findIndex(item => item.assigneeName?.includes(sUserId)) : -1;
        const userIndex = commonUtils.isNotEmptyArr(historyList) ? 0 : -1;
        if(userIndex > -1) {
          historyList[userIndex].comment = data.approved ? '已同意' : '已驳回';
          historyList[userIndex].assigneeName = sUserId;
          historyList[userIndex].endTime = moment().format('YYYY-MM-DD HH:mm:ss');

          /* 关闭页签 */
          const currentPaneIndex = panes?.findIndex(item => item.key === currentPane.key);
          const newPanes = [];
          if (currentPaneIndex > 0) {
            panes.forEach((item, index) => {
              if (index !== currentPaneIndex) {
                newPanes.push(item);
              }
            });
            this.props.dispatch({ type: 'app/removePane', payload: { changePanes: newPanes, currentPane: panes[currentPaneIndex - 1] } });/* 关闭当前页签 */
          }
          const iframe = document.getElementById('iframe1');
          if(commonUtils.isNotEmptyObject(iframe)) {
            const iframeWindow = iframe.contentWindow;
            // 调用iframe中的函数
            // let iframeDoc = iframe.contentWindow || iframe.contentDocument;
            // if (iframeDoc.document) iframeDoc = iframeDoc.document; // 处理IE兼容性
            iframeWindow.location.reload(); // 刷新iframe中的页面
          }
          // 确保进度计数到101后清除loading状态
          this.setState({
            historyNewList: historyList,
            bHandleShow: false,
            flowLoading: false,
            progressCount: 101
          });
        }

      } else {
        this.props.getServiceError(sReturn);
        // 操作失败时清除loading状态
        this.setState({ flowLoading: false });
      }
    }else {
      message.warn('操作异常！')
      // 操作异常时清除loading状态
      this.setState({ flowLoading: false });
    }

  }

  /* 转办弹出转办人弹出窗  */
  transferHandler  =  (btnName ) => {
    const bTransferUserVisible = true;
    this.setState({
      bTransferUserVisible
    })
  }
  /* 执行转办逻辑 */
  transferCall = async () => {
    const { delegateToUserId, delegateToUser} = this.state;
    const { app } = this.props;
    const { currentPane, panes, userinfo } = app;
    const sFlowData = currentPane?.sFlowData; /* 业务流完整数据源 */
    const sBrandsId = userinfo?.sBrandsId;
    const sSubsidiaryId = userinfo?.sSubsidiaryId;
    const sUserId = userinfo?.sUserName;
    let sFlowObj = {};
    if (commonUtils.isNotEmptyObject(sFlowData)) {
      const sFlowArr = [JSON.parse(sFlowData.toString())];
      if (commonUtils.isNotEmptyArr(sFlowArr)) {
        sFlowObj = sFlowArr[0];
      }
    }
    const userList = [];
    const taskId = sFlowObj?.taskId;
    const data =[];
    if(commonUtils.isEmptyObject(delegateToUser)) {
      message.warn('请选择转办人！')
      return;
    }
    if(delegateToUser === sUserId){
      message.warn('请选择非自己的待办人');
      return;
    }
    this.setState({flowLoaing:true});
    let redata = {
      taskId: taskId,
      delegateToUser: delegateToUser,
      delegateToUserId: delegateToUserId
    };
    const url = commonConfig.server_host + "process/delegatePhone/"+sUserId+"/"+sBrandsId+"/"+sSubsidiaryId;
    const { token }= this.props;
    const sReturn = (await commonServices.postValueService(token, redata, url)).data;
    if(commonUtils.isNotEmptyObject(sReturn)) {
      if (sReturn.code > 0 || sReturn.code === 0) {
        message.success('转办成功！');
        /* 关闭页签 */
        const currentPaneIndex = panes?.findIndex(item => item.key === currentPane.key);
        const newPanes = [];
        if (currentPaneIndex > 0) {
          panes.forEach((item, index) => {
            if (index !== currentPaneIndex) {
              newPanes.push(item);
            }
          });
          this.props.dispatch({ type: 'app/removePane', payload: { changePanes: newPanes, currentPane: panes[currentPaneIndex - 1] } });/* 关闭当前页签 */
        }
        const iframe = document.getElementById('iframe1');
        if(commonUtils.isNotEmptyObject(iframe)) {
          const iframeWindow = iframe.contentWindow;
          // 调用iframe中的函数
          iframeWindow.location.reload(); // 刷新iframe中的页面
        }
        this.props.onSaveState({ bDelegate: true}); /* 已转办 */
        this.setState({flowLoaing:false});
      } else {
        this.props.getServiceError(sReturn);
      }
    } else {
      message.warn('操作异常！')
    }
    this.setState({ bTransferUserVisible:false })
  }
  handleCancelModal = (modelVisible) => {
    this.setState({ bTransferUserVisible:false })
  }
  /* 设置textareaValue */
  handleTextareaChange = (e) => {
    this.setState({
      textareaValue: e.target.value,
    });
  }
   handleSelectChange = (value) => {
     this.setState({
       delegateToUserId: value,
       delegateToUser: value
     });
  };
  handleInputChange = (e,  name) => {
    const inputValue = e.target.value;
    this.setState({
      [name]: inputValue
    });
  };

  handleOptionChange = (value, option, name) => {
    const sFieldName = name;
    const sKey = option?.id;
    this.setState({
      [sFieldName + "_sRealName"]:value,
      [sFieldName]: sKey
    });
  };

  render() {
    const { bTransferUserVisible, historyNewList, flowLoading }= this.state;
    let { bHandleShow =true }= this.state;
    const { app, masterConfig } = this.props;
    const { currentPane } = app;
    const sFlowData = currentPane?.sFlowData; /* 业务流完整数据源 */
    let sFlowObj = {};
    if (commonUtils.isNotEmptyObject(sFlowData) && commonUtils.isJSON(sFlowData)) {
      sFlowObj = JSON.parse(sFlowData.toString());
      // const sFlowArr = JSON.parse(sFlowData.toString());
      // if (commonUtils.isNotEmptyArr(sFlowArr)) {
      //   sFlowObj = sFlowArr[0];
      // }
    }
    const isHandle = sFlowObj?.isHandle;
    // console.log('sFlowObj:', sFlowObj);
    // const bHandleShow = sFlowObj?.bHandleShow; /* 是否展示按钮及审批意见区域 */
    if(bHandleShow) {
      bHandleShow = !sFlowObj.isHandle;
    }
    let sFlowTitle = sFlowObj?.title; /* 审批标题 */
    const dataList = sFlowObj?.dataList; /* 审批数据源 */
    let  historyList = sFlowObj?.historyList; /* 审批流程 */
    if(commonUtils.isNotEmptyArr(historyNewList)) {
      historyList = historyNewList;
    }
    let sCheckInfo = '审批记录';
    if(commonUtils.isEmptyObject(sFlowObj)) {
      bHandleShow = false;
      sFlowTitle ='暂无审批信息';
      sCheckInfo = '';
    }
    let userList =  commonUtils.isNotEmptyArr(sFlowObj?.userData)? sFlowObj?.userData : []; /* 转办人 */
    const dataDynamicList = commonUtils.isNotEmptyArr(dataList) ? dataList.filter(item  =>  item.name !=='sEmployeeName') : [];
    const sBillNoObj =commonUtils.isNotEmptyArr(dataList) ? dataList.find(item => item.name === 'sBillNo') : null; /* 申请人员 */
    const sBillNo = commonUtils.isNotEmptyObject(sBillNoObj) ? sBillNoObj.value : '';
    const sApplyObj = commonUtils.isNotEmptyArr(dataList) ? dataList.find(item => item.name === 'sEmployeeName') : null; /* 申请人员 */
    const sApplyName = commonUtils.isNotEmptyObject(sApplyObj) ? sApplyObj.value : '';

    const sApplyDateObj = sFlowObj?.bizFlowVo; /* 申请人员 */
    const sApplyDate = commonUtils.isNotEmptyObject(sApplyDateObj) ? sApplyDateObj.applyTime : '';
    const historyItem = [];
    if(commonUtils.isNotEmptyObject(historyList)) {
      historyList.forEach((item) => {
        const activityName = item.activityName;
        const time = item.endTime;
        const status = item.comment;
        const assigneeName = item.assigneeName; /* 同意人 */
        const flowMemo = item.memo ; /* 例： 备注：项目加急，需要加班 */
        const sDescription = (
          <div>
            <div className={styles.flowDescription}>
              <div className={styles.sPersonInfo}>
                <div className={styles.sPersonPic}> <img style={{ width: '30px', height: '30px' }} alt="头像" src={flowPicture2} /> </div>
                <div className={styles.sPersonName}>{assigneeName} </div>
              </div>
              <div className={styles.sPersonStatus}>{status}·{time} </div>
            </div>
            <div className={styles.floweExtra}>
               {flowMemo}
            </div>
          </div>
        );
        const obj =  {
          title: activityName,
          description: sDescription,
          icon: <UserOutlined />,
        }
        historyItem.push(obj)
      })
    }
    return (
      <Layout className={styles.examInfo}>
        <Spin spinning={flowLoading}>
        <Content className={styles.content}>
          <div className={styles.cardTitle}>{sFlowTitle}</div>
          <div className={styles.cardBox}>
            {
              commonUtils.isNotEmptyObject(dataList) ?
                <div className={styles.cardBill}>
                  {
                    commonUtils.isNotEmptyArr(sApplyName) ?
                      <div className={styles.cardLine}>
                        <div className={styles.cardColumn}>申请人:</div>
                        <div className={styles.cardValue}>{sApplyName}</div>
                      </div>
                      : ''
                  }
                  <div className={styles.cardLine}>
                    <div className={styles.cardColumn}>申请时间:</div>
                    <div className={styles.cardValue}>{sApplyDate}</div>
                  </div>
                  {
                    dataDynamicList && dataDynamicList.map((child) => {
                      const name = child.name;
                      const title = child.title;
                      let value = child.value;
                      let bEdit = !child.bEdit; /* 是否编辑 */
                      const sRealValue = child.sRealValue;
                    /* 如果 isHandle 为 true,代表只能查看， 就不允许编辑 */
                    if(bEdit) {
                      bEdit = !isHandle;
                    }
                    let bHtml =false;
                    if(commonUtils.isNotEmptyObject(value)) {
                      if(value.includes('br')) {
                        value = String(value).replace(/<br\s*\/?>/gi, '\n');
                      }
                      if(value.includes('&lt')) {
                        value=  String(value).replace(/&lt;br\s*\/?&gt;/gi, '\n')
                      }
                      bHtml = true;
                    }
                    const type= child.type; /* 文本类型 */
                    const bSelect = child.bSelect; /* 是否下拉 */
                    const selectList = child.selectList;
                    const selectConfig = bSelect && commonUtils.isNotEmptyObject(masterConfig) ? masterConfig.gdsconfigformslave.filter(item => item.sName === name) : [];
                    const showDropDownStr = commonUtils.isNotEmptyArr(selectConfig) && commonUtils.isNotEmptyObject(selectConfig[0].showDropDown) ?
                        selectConfig[0].showDropDown : []; /* 可编辑的下拉 */
                        const showDropDown = commonUtils.isNotEmptyObject(showDropDownStr)  && commonUtils.isJSON(showDropDownStr) ? [JSON.parse(showDropDownStr)] : [];
                      return (
                        <div className={styles.cardLine}>
                          <div className={styles.cardColumn}>{title}</div>
                          {
                             bEdit && type === 's' && !bSelect ?
                                 <div className={styles.cardValue}><Input placeholder="请输入" id={name} onChange={(e) => this.handleInputChange(e, name)} /> </div> :
                               bEdit && type === 's' && bSelect ?
                                 <div className={styles.cardValue}> <Select
                                   id ={name}
                                   defaultValue=""
                                   style={{ width: 200 }}
                                   disabled={false}
                                   options={selectList}
                                   onChange={(value, option) => this.handleOptionChange(value, option, name)}
                                   /></div> :
                                 !bEdit && type === 's' && bSelect ?
                                   <div className={styles.cardValue}> {sRealValue}</div> :
                                 bEdit && type === 'm' && !bSelect ?
                                   <TextArea
                                     className={styles.memo}
                                     rows={3}
                                     id ={name}
                                     onChange={(e) => this.handleInputChange(e, name)}
                                     placeholder="请输入"
                                   /> :
                               <div className={styles.cardValue}>
                                 {
                                   type === 's' && (name?.includes('sProcessName') || name?.toLowerCase().indexOf('memo') > -1)  ?
                                     <pre className={styles.preStyle}>  {value} </pre> : bHtml ? <pre className={styles.pre}>{value} </pre>  : value
                                 }

                               </div>
                          }

                        </div>
                      );
                    })
                  }

                </div>
                : ''
            }


          </div>

          <div className={styles.flowInfo} >
            <div className={styles.flowTitle}>{sCheckInfo}</div>
            <div className={styles.flowStep}>
              {/*{*/}
              {/*  historyList && historyList.map((child) => {*/}
              {/*    const title = child.title;*/}
              {/*    const value = child.value;*/}
              {/*    return (*/}
              {/*      <div className={styles.cardLine}>*/}
              {/*        <div className={styles.cardColumn}>{title}</div>*/}
              {/*        <div className={styles.cardValue}>{value}</div>*/}
              {/*      </div>*/}
              {/*    );*/}
              {/*  })*/}
              {/*}*/}
              <Steps
                direction="vertical"
                current={1}
                size="large"
                items={historyItem}
              />
            </div>
          </div>

          <div className={styles.flowComments} style={{ display: bHandleShow ? 'block' : 'none'}}>
            <div className={styles.splitLine} />
            <div className={styles.cardLine}>
              <div style={{ marginLeft: '12%', marginTop: '3%', width: '100%' }} className={styles.cardValue}>
                <TextArea
                  className={styles.memo}
                  rows={3}
                  id='comment'
                  onChange={this.handleTextareaChange}
                  value={this.state.textareaValue}
                  placeholder="请输入审批意见"
                />
              </div>
            </div>
          </div>

          {
            bHandleShow ?
              <div className={styles.cardAgree} style={{ display: 'flex', paddingleft: '9%' }}>
                <button onClick={() => this.transferHandler('transfer')} className={styles.btnTransfer}>转办</button>
                <button onClick={() => this.submitHandler('reject')} className={styles.btnRefuse}>驳回</button>
                <button onClick={() => this.submitHandler('agree')} className={styles.btnAgree}>同意</button>
              </div> : ''
          }

          {
            bTransferUserVisible ?
              <Modal
                open={bTransferUserVisible }
                title='转办人'
                width="20%"
                // visible={transferUserVisible}
                 onCancel={() => this.setState({ bTransferUserVisible : false})}
                // afterClose={handleCancel}
                footer={null}
              >
                <div style={{ width: '100%', height:'100px', padding:'20px 30px' }}>
                  <Select
                    id ='transferUserId'
                    defaultValue=""
                    style={{ width: 200 }}
                    disabled={false}
                    options={userList}
                    onChange={this.handleSelectChange}
                  />
                </div>
                <div className='ant-modal-footer' style={{ padding: '8px 0 0 0' }}>
                  <Button key="back" onClick={() => this.handleCancelModal('bTransferUserVisible')}>取消</Button>
                  <Button key="submit" type="primary" onClick={() => this.transferCall()}>确认</Button>
                </div>
              </Modal>
              : ''
          }

        </Content>
        </Spin>
      </Layout>
    );
  }
}

export default CommonExamInfo;
