import { message } from "antd/lib/index";
import { Button, Descriptions, Badge, Popconfirm, Row, Col, Form, Input, Select, Table } from 'antd';
import React from 'react';
import { initFilter, extendRule, extendInclude, setDataFieldValue, guid, initQueryFilter, onBeforeSaveHandleRecordLog } from "../../../utils/common";
import { ExportToExcel } from '@woowalker/feui'
import styles from '../HI/StepForm.css';
import ReactToPrint from "react-to-print";
import moment from 'moment';
import config from "../../../config.js";
import XLSX from 'xlsx';
import { connect } from 'dva';



class FoTeamActivityShowPrint extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      data: null,
      item: null,
      enumData: null,
      btndisplay: 'none',
      readDisplay: 'none',
      isFinished: 'none',
      isMobile: false
    }
  }

  componentDidMount() {
    if (window.navigator.userAgent.indexOf("Windows") < 1) {
      this.setState({ isMobile: true })
    }
    if (this.props.data?.id)
      this.loadData(this.props.data?.id);
  }

  componentWillReceiveProps(NextProps) {
    if (NextProps.data?.id && this.props.data?.id != NextProps.data?.id) {
      this.loadData(NextProps.data?.id);
    }
  }

  onTableBtnExport() {
    // let TableWrap = document.getElementById('table1' + this.props.record.ID);
    let TableWrap = document.getElementById('table1');
    let Table = TableWrap.getElementsByTagName('table1')[0];
    const wb = XLSX.utils.table_to_book(Table);
    XLSX.writeFile(wb, this.props.record.Nav_Department.NAME + ".xlsx")
  }

  onTableBtnAgree() {
    onBeforeSaveHandleRecordLog(this.props, 'FO010', 'FO010_onTableBtnAgree')
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FO/FOTeamActivity/TeamActivityUserUpdate',
      payload: {
        ID: this.props.data.id,
        //ORG_ID: this.props.data.OrgId,
        TaskID: this.props.data.TaskID,      //传参到后端（消息表ID）  
      },
      onComplete: (ret) => {
        if (ret) {
          message.success('签到成功！');
          this.BtnClose();
        }
      }
    })
  }
  onTableBtnRead() {
    onBeforeSaveHandleRecordLog(this.props, 'FO010', 'FO010_onTableBtnRead')
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'FO/FOTeamActivity/TeamActivityUserRead',
      payload: {
        ID: this.props.data.id,
        TaskID: this.props.data.TaskID,      //传参到后端（消息表ID）  
      },
      onComplete: (ret) => {
        if (ret) {
          message.success('已阅成功！');
          this.BtnClose();
        }
      }
    })
  }
  BtnClose = () => {
    if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
      this.props.data.onCancel();
  }

  //加载数据(传过来的参数都在props里面，包括登录信息)
  loadData = (id) => {
    var orgId = this.props.login ? this.props.login.OrgId : '';   //登录后有存储登录信息

    let json = initFilter(orgId);
    extendRule(json, 'ID', 1, id);    //ID=‘’，字段，等于，条件值， 1代表=，2代表不等于，3小于，4小于等于，5大于，6大于等于，7以开始的Like,8以结束的Like，9包含 
    extendInclude(json, 'Nav_Taem');
    extendInclude(json, 'Nav_User');
    extendInclude(json, 'Nav_TeamActivityUser.Nav_User.Nav_UserSignFiles.Nav_ImgFile.Nav_File');
    extendInclude(json, 'Nav_TeamActivityFile.Nav_ImgFile.Nav_File');
    json.IgnoreDataRule = true;
    let attendanceAry = [], leaveAry = [];
    let that = this;
    let btndisplay = 'none';
    this.state.readDisplay = 'none';

    this.props.dispatch({
      type: 'app/getDataByPost',
      payload: json,
      url: 'FO/TeamActivity/Get',
      onComplete: (ret) => {    //返回查询结果ret
        if (ret) {    //判断是否有记录

          //data?.Nav_TeamActivityUser.map(item => {    //当data有值时遍历(map)data记录集
          ret?.Nav_TeamActivityUser.forEach(item => {  //当data有值时遍历(forEach)data记录集
            if (item.ATTEND_STATUS === 1) {   //参会人员
              attendanceAry.push(item.Nav_User.NAME);   //将人员添加到attendanceAry数组
            } else if (item.ATTEND_STATUS === 2) {      //缺席人员,
              leaveAry.push(item.Nav_User.NAME);        //将人员添加到attendanceAry数组
            }
            //if (item.Nav_User.ID.toLowerCase() == that.props.login.userId.toLowerCase() && item.TA_STATUS===1 && item.ATTEND_STATUS === 1 && item.SIGN_IN_STATUS === 0) {
            if (item.Nav_User.ID.toLowerCase() == that.props.login.userId.toLowerCase() && item.ATTEND_STATUS === 1 && item.SIGN_IN_STATUS === 0 || !(this.props.data.tableKey == "2" || this.props.data.tableKey == undefined)) {
              btndisplay = 'inline';    //签到按扭显示变量
            }
            if (item.Nav_User.ID.toLowerCase() == that.props.login.userId.toLowerCase() && item.ATTEND_STATUS === 2) {
              this.state.readDisplay = 'inline';
            }
          })
          this.setState({   //设置setState全局变量
            data: ret,      //将ret对象赋值给data, data供页面调用
            attendance: attendanceAry,
            leave: leaveAry,
            btndisplay: btndisplay
          })
          if (ret.TA_STATUS == 2) {
            this.setState({
              isFinished: 'inline'
            })
          }
        }else
        { message.error('数据加载获取失败，请联系管理员排查!');}
      }
    });
  }

  //渲染页面
  render() {
    const { data, isMobile } = this.state;
    return <div>
      <div style={{ marginTop: '10px' }}>
        <table>
          <tr>
            <td><ReactToPrint trigger={() => <Button type={'default'} icon={'printer'} style={{ marginLeft: '20px', display: this.state.isFinished }} >打印</Button>} content={() => this.componentRef}
              pageStyle=".printDIV { padding:0 40px;} img{width :120px}"
            /></td>
            <td style={{ marginLeft: '20px', display: this.state.isFinished }}><ExportToExcel fileName='班组安全记录活动表' tableId='table1' /></td>
            <td><Button type="default" style={{ marginLeft: isMobile ? '0' : '20px', display: this.state.btndisplay }} onClick={() => this.onTableBtnAgree()} icon="check" >签到</Button></td>
            <td><Button type="default" style={{ marginLeft: isMobile ? '0' : '20px', display: this.state.readDisplay }} onClick={() => this.onTableBtnRead()} icon="check" >已阅</Button></td>

            {/* <td><Button onClick={() => this.BtnClose()} icon="close-circle" >关闭</Button></td> */}
          </tr>
        </table>
      </div>

      {/* 班组安全活动记录表 */}
      <div ref={el => (this.componentRef = el)} style={{ padding: isMobile ? '0px 0px 20px 0px' : '20px' }} id={'tableId' + this.props.id}>
        <h1 style={{ textAlign: 'center' }}>班组安全活动记录表</h1>
        {
          data ? <div>
            <table id={'table1'} style={{ width: '100%', borderTop: '1px solid #333', borderLeft: '1px solid #333' }} className={styles.PrintForm}>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动主题</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{data.TITLE}</td>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动日期</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{moment(data.ACTIVITY_TIME).format('YYYY-MM-DD')} </td>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动地点</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{data.ADDRESS}</td>
              </tr>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>班组名称</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{data.Nav_Taem ? data.Nav_Taem.NAME : ''}</td>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>记录人</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{data.Nav_User ? data.Nav_User.NAME : ''}</td>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动时长</td>
                <td colSpan={4} rowSpan={1} style={{ textAlign: 'left' }}>{data.DURATION}</td>
              </tr>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>参与人员</td>
                <td colSpan={16} rowSpan={1} style={{ textAlign: 'left' }}> {
                  data.Nav_TeamActivityUser && data.Nav_TeamActivityUser.map((rs, i) => {
                    if (rs.ATTEND_STATUS === 1) {   //参会人员
                      if (rs.SIGN_IN_STATUS == 1) {    //已签到
                        return rs.Nav_User.NAME + " ";
                      } else {
                        return (<span style={{color:'red'}}>{ rs.Nav_User.NAME + " "}</span>);
                      }
                    }
                  })
                }</td>
              </tr>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动记录</td>
                <td colSpan={16} rowSpan={1} style={{ textAlign: 'left', height: '150px' }}>{data.ACTIVITY_CONTENT}</td>
              </tr>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>附件</td>
                <td colSpan={16} rowSpan={1} style={{ textAlign: 'left' }}>
                  {
                    data.Nav_TeamActivityFile && data.Nav_TeamActivityFile.map((item, i) => {
                      return <a href={config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH} target='_blank'>{item.Nav_ImgFile.FILE_NAME}</a>
                    })
                  }
                </td>
              </tr>
              <tr>
                <td colSpan={2} rowSpan={1} className={styles.fontBold}>活动签到</td>
                <td colSpan={16} rowSpan={1} style={{ textAlign: 'left', height: '150px' }}>{
                  data.Nav_TeamActivityUser && data.Nav_TeamActivityUser.map((item, i) => {
                    if (item.ATTEND_STATUS == 1 && item.SIGN_IN_STATUS == 1) {    //参会人员与已签到的才显示  
                      if (item.Nav_User.Nav_UserSignFiles != null && item.Nav_User.Nav_UserSignFiles[0] != null) {
                        return item.Nav_User.Nav_UserSignFiles && <img width={'150px'} src={config.picServerHost + item.Nav_User.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} />
                      } else {
                        return item.Nav_User.NAME
                      }
                    }
                  })
                }
                </td>
              </tr>
            </table>
            {/* <Descriptions title="" size="middle" bordered className={isMobile?styles.description:null}>
              <Descriptions.Item label="编号">{data.CODE}</Descriptions.Item>
              <Descriptions.Item label="活动日期">{moment(data.ACTIVITY_TIME).format('YYYY-MM-DD')}</Descriptions.Item>
              <Descriptions.Item label="活动时长">{data.DURATION}</Descriptions.Item>
              <Descriptions.Item label="活动主题" span={3}>{data.TITLE}</Descriptions.Item>
              <Descriptions.Item label="活动地点">{data.ADDRESS}</Descriptions.Item>
              <Descriptions.Item label="班组名称">{data.Nav_Taem ? data.Nav_Taem.NAME : ''}</Descriptions.Item>
              <Descriptions.Item label="记录人">{data.Nav_User ? data.Nav_User.NAME : ''}</Descriptions.Item>              
              <Descriptions.Item label="缺席人员" span={3}>{this.state.leave.join(',')}</Descriptions.Item>
              <Descriptions.Item label="参会人员" span={3}>{
                data.Nav_TeamActivityUser && data.Nav_TeamActivityUser.map((rs, i) => {
                  if (rs.ATTEND_STATUS === 1) {   //参会人员
                    if (rs.SIGN_IN_STATUS == 1) {    //已签到
                      return rs.Nav_User.NAME + " ";
                    } else {
                      return (<span style={{color:'red'}}>{ rs.Nav_User.NAME + " "}</span>);
                    }
                  }
                })}</Descriptions.Item>
              <Descriptions.Item label="活动内容" span={3}>{data.ACTIVITY_CONTENT}</Descriptions.Item>
              <Descriptions.Item label="附件" span={3}>
                {
                  data.Nav_TeamActivityFile && data.Nav_TeamActivityFile.map((item, i) => {
                    return <a href={config.picServerHost + item.Nav_ImgFile.Nav_File.FILE_PATH} target='_blank'>{item.Nav_ImgFile.FILE_NAME}</a>
                  })
                }
              </Descriptions.Item>
              <Descriptions.Item label="活动签到" span={3}>
                {
                  data.Nav_TeamActivityUser && data.Nav_TeamActivityUser.map((item, i) => {
                    if (item.ATTEND_STATUS == 1 && item.SIGN_IN_STATUS == 1) {    //参会人员与已签到的才显示  
                      if (item.Nav_User.Nav_UserSignFiles != null && item.Nav_User.Nav_UserSignFiles[0] != null) {
                        return item.Nav_User.Nav_UserSignFiles && <img width={'150px'} src={config.picServerHost + item.Nav_User.Nav_UserSignFiles[0].Nav_ImgFile.Nav_File.FILE_PATH} />
                      } else {
                        return item.Nav_User.NAME + " "
                      }
                    }
                  })
                }

              </Descriptions.Item>
            </Descriptions> */}

          </div> : null
        }
      </div>
    </div>
  }
}
export default connect(({ login }) => ({ login }))(FoTeamActivityShowPrint) 
