import React, {PureComponent} from 'react';
import {connect} from 'dva';
import store from "store";
import style from "styled-components";
import {Select, Input, Button, DatePicker, Icon, Popover, Radio, message, Upload, Drawer} from 'antd';
import {Link} from 'dva/router';
import * as api from "../../../services/api";
import PTable from "../../../components/Pro/PTable";
// import Drawer from 'react-motion-drawer';
import * as request from "../../../utils/request.js";
import bcx_utils from "../../../common/bcx_utils";
import moment from "moment";


const Option = Select.Option;
const {MonthPicker} = DatePicker;
const RadioGroup = Radio.Group;

@connect(state => ({
  global: state.global
}))
@connect(state => ({
  monitor: state.monitor,
}))
export default class ReportGet extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      type: this.props.match.params.type || "1",//2为查看月报表，1为查看普遍// 报表
      reportId: this.props.match.params.reportId,
      columns: [],//动态表头
      pageParm: {
        reportId: this.props.match.params.reportId,
        reportMonth: "",
        pageNumber: "1",
        pageSize: "10",
      },//分页请求参数
      forceUpdate: false,
      ifDrawerReport: false,
      ifDrawerExport: false,
      radioValue: 1,
      updataData: {//即将更新的 input 框内容
        fieldCode: "",
        fieldValue: "",
        id: ""
      },
      uploadResponse: [],//上传文件 提示内容
      shouldMoney: "",//应发工资
      reportSet: {
        reportType:"1",
        reportName: "",
        remark: "",
        isSumSalary: "1"
      },//报表设置
    };
  }

  /******************************生命周期******************************/

    //查看报表有2种模式，分别为查看月报表，查看普通报表
  componentDidMount = () => {
    this.init();
  };
  componentWillUnmount = () => {
    if (this.timeInput) clearTimeout(this.timeInput);
  };
  init = () => {

    //判断是哪种模式
    if (this.state.type === "2") {
      const {pageParm} = this.state;
      pageParm.reportMonth = moment().format().slice(0, 7);
      this.setState({pageParm}, () => this.allAjax());
    } else if (this.state.type === "1") {
      this.allAjax();
    }
  };

  allAjax = () => {
    const {reportId} = this.state;
    this.enterpriseSalaryComReportReportDetail(reportId);
    this.enterpriseSalaryComReportReport(reportId);
    this.enterpriseSalaryComReportSumActualWage();
  };

  /******************************ajax请求******************************/
    // 根据报表id获得报表表头
  enterpriseSalaryComReportReportDetail = (reportId) => {
    api.enterpriseSalaryComReportReportDetail({reportId}).then((data) => {

      //table 中 input 修改记录保存
      const Content = ({record, fieldCode, column, index}) =>
        (
          <InputChange>
            <Input onChange={this.inputChange.bind(this, record, fieldCode)}
                   ref={ref => this[`input${column}${index}`] = ref}/>
            <div className="btn" onClick={this.enterpriseSalaryComReportUpdateReportInfo.bind(this, column, index)}>
              修改
            </div>
            <div className="btn" onClick={this.inputCancel.bind(this, column, index)}>
              放弃
            </div>
          </InputChange>
        );

      const columns = data.data.map((val, key) => {
        //判断是否可编辑    Popover设置动态 visible
        if (val.isEdit === "1") {
          return {
            title: val.fieldName,
            dataIndex: val.fieldCode,
            key,
            render: (text, record, index) => (
              <Popover placement="bottomLeft"
                       trigger="click"
                       content={<Content {...{record, fieldCode: val.fieldCode, column: key, index}}/>}
                       visible={this.state[`visible${key}${index}`]}
                       onVisibleChange={this.handleVisibleChange.bind(this, key, index)}
              >
                <div style={{cursor: "pointer"}}>{text}</div>
              </Popover>
            )
          }
        } else {
          return {
            title: val.fieldName,
            dataIndex: val.fieldCode,
            key,
          }
        }
      });
      this.setState({columns});
    }, (err) => {
      console.log(err);
    });
  };

  //修改单条报表数据中的单项
  enterpriseSalaryComReportUpdateReportInfo = (column, index) => {
    const {updataData} = this.state;
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      if (updataData.fieldValue.trim() === "") {
        message.error("不能为空", 1.5, () => resolve(false));
        return;
      } else {
        api.enterpriseSalaryComReportUpdateReportInfo(updataData).then((data) => {
          resolve(false);
          this.setState({forceUpdate: true}, () => {
            this.setState({forceUpdate: false});
          });
          this.inputCancel(column, index);
        }, (err) => {
          resolve(false);
          this.setState({forceUpdate: true});
          // this.inputCancel();
        });
      }
    }))
  };


  // 修改报表
  enterpriseSalaryComReportUpdateCompanyReport = () => {
    const {reportSet, reportId} = this.state;
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {
      if (reportSet.reportName == "") {
        message.error("报表名字不能为空", 1.5, () => resolve(false));
        resolve(false);
        return;
      }
      if (reportSet.remark == "") {
        message.error("报表说明不能为空", 1.5, () => resolve(false));
        resolve(false);
        return;
      }
      let ajaxData = {...reportSet, payReportId: reportId};
      api.enterpriseSalaryComReportUpdateCompanyReport(ajaxData).then((data) => {
        //message.success(data.msg);
        this.setState({ ifDrawerExport:false });
        this.init();
        resolve(false);
      }, (err) => {
        message.error(err.msg);
        resolve(false);
      });
    }))
  };

  // 获得实发工资总额
  enterpriseSalaryComReportSumActualWage = () => {
    let ajaxData = {
      reportId: this.state.reportId,
      reportMonth: this.state.pageParm.reportMonth
    };
    api.enterpriseSalaryComReportSumActualWage(ajaxData).then((data) => {
      this.setState({shouldMoney: data.data});
    }, (err) => {
      console.log(err);
    });
  };
  //根据报表id获得报表设置
  enterpriseSalaryComReportReport = (reportId) => {
    api.enterpriseSalaryComReportReport({reportId}).then(
      (data) => {
        let {reportName, remark, isSumSalary,reportType} = data.data;
        this.setState({
          reportSet: {
            reportName,
            remark,
            isSumSalary,
            reportType
          }
        });
      },
      (err) => {
        console.log(err);
      }
    );
  };


  /******************************相关事件******************************/

  onMonthPickerChange = (date, dateString) => {
    if (dateString === "") return;
    let pageParm = {...this.state.pageParm};
    pageParm.reportMonth = dateString;
    this.setState({pageParm}, () => {
      this.enterpriseSalaryComReportSumActualWage();
    });
  };

  //table表格 change，这里设置 Popover初始化参数
  dateTableChange = (data) => {
    let arr = data.data;
    let colum = this.state.columns;
    colum.map((v, key) => {
      arr.map((val, index) => {
        this.setState({
          [`visible${key}${index}`]: false
        });
      })
    });
  };


  //table 中 input 修改记录保存
  inputChange = (record = {}, fieldCode = "", e) => {

    const updataData = {...this.state.updataData};

    if (!fieldCode) {
      return;
    } else {
      updataData.fieldValue = e.target.value;
      updataData.fieldCode = fieldCode;
      updataData.id = record.comPayReportInfoId;
      this.setState({updataData});
    }
  };

  //table 中 input 修改记录取消
  inputCancel = (key, index) => {
    this.setState({
      updataData: {
        fieldCode: "",
        fieldValue: "",
        id: ""
      },
      [`visible${key}${index}`]: false,
    });
    this[`input${key}${index}`].input.value = "";
  };

  //Popover打开
  handleVisibleChange = (key, index, visible) => {
    this.setState({
      [`visible${key}${index}`]: visible
    });
    this.timeInput = setInterval(() => {
      if (this[`input${key}${index}`]) {
        clearTimeout(this.timeInput);
        this[`input${key}${index}`].focus();
      }
    }, 200);
  };


  drawerReportOnChange = (ifDrawerReport) => {
    this.setState({ifDrawerReport});
  };

  drawerExportOnChange = (ifDrawerExport) => {
    this.setState({ifDrawerExport});
  };
  //报表设置输入框
  reportSet = (e) => {
    const reportSet = {...this.state.reportSet};
    reportSet[e.target.name] = e.target.value.trim();
    this.setState({reportSet});
  };


  //报表设置radio
  onRadioChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  //下载 excel
  downExcel = () => {
    window.open(`${request.getHostByPath('/enterprise')}/enterprise/salary/com-report/export-report?reportId=${this.state.reportId}`, "_self");
  };


  /******************************render******************************/

  renderTable = () => {
    const columns = [...this.state.columns];
    let newProp = {};
    if (columns.length > 10) {
      columns[0].fixed = "left";
      columns[0].width = 80;
      newProp = {
        scroll: {x: 1400}
      };
    }
    if (columns.length > 14) {
      newProp = {
        scroll: {x: 1600}
      };
    }
    if (columns.length > 20) {
      newProp = {
        scroll: {x: 2000}
      };
    }
    return (
      <PTable
        columns={columns}
        url="enterpriseSalaryComReportReportInfo"
        pageParm={this.state.pageParm}
        dateChange={this.dateTableChange}
        forceUpdate={this.state.forceUpdate}
        showTotal
        {...newProp}
      />
    );
  };

  //文件上传
  renderUploadExcel = () => {
    const uploadExcel = {
      name: 'xfile',
      action: request.getHostByPath('/enterprise') + '/enterprise/salary/com-report/import-report-info?comId=' + this.props.global.companyInfo.comId,
      headers: {
        authorization: store.get("saas")["access_token"],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

      },
      data: {
        reportId: this.state.reportId,
        reportMonth: this.state.pageParm.reportMonth,
      },
    };

    const beforeUpload = file => {
      let ifError = true;
      if (file.name.indexOf("xls") == -1 && file.name.indexOf("xlsx") == -1) {
        message.error('请上传xls或xlsx文件!');
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = info => {
      if (info.file.status === 'uploading') {
        this.setState({loading: true});
        return;
      }
      if (info.file.status === 'done') {
        this.setState({uploadResponse: info.file.response.data});
        if (info.file.response.retType == 0) {
          message.success(info.file.response.msg);
          this.setState({forceUpdate: true}, () => {
            this.setState({forceUpdate: false});
          });
        }
      }
    };

    return (
      <div className="p1" style={{fontSize: 12}}>
        <Upload onChange={UploadChange}
                beforeUpload={beforeUpload}
                {...uploadExcel}>
          <Button size="small" style={{marginRight: "8px"}}><Icon type="upload"/>上传文件</Button>支持扩展名：.xls／.xlsx
        </Upload>

      </div>
    );

  };

  render() {
    const {type, shouldMoney, reportSet, uploadResponse} = this.state;
    const reportMonth = this.state.pageParm.reportMonth;
    const year = reportMonth.slice(0, 4);
    const month = reportMonth.slice(5, 7);
    let yearAndMonth;
    let yearAndMonthSplit;
    if (reportSet.reportType === "2") {
      yearAndMonth = `${year}年${month}月`;
      yearAndMonthSplit = `|`;
    }

    return (
      <div>
        <Content>
          {/* 搜索条件面板 */}
          <div className="searchpanel">
            {type === "2" &&
            <div style={{display: "inline-block"}}>
              <span>报表时间：</span>
              <MonthPicker onChange={this.onMonthPickerChange}
                           placeholder="请选择月份"
                           defaultValue={moment()}
                           style={{width: 214, marginRight: 17}}/>
            </div>
            }
            {/*<Button type="primary">返回查看</Button>*/}
            <Button style={{marginRight: 17}} onClick={() => this.setState({ifDrawerExport: true})}>报表设置</Button>
            <Button style={{marginRight: 17}} onClick={() => this.setState({ifDrawerReport: true})}>导入数据</Button>
            <Button style={{marginRight: 17}} onClick={() => this.props.history.push(`/adminis/labor`)}>返回</Button>
          </div>
          {reportSet.isSumSalary === "1" && (
            <Title>
              {!shouldMoney && "暂无相关数据"}
              {shouldMoney && (
                <div>
                  {yearAndMonth}<span className="split">{yearAndMonthSplit}</span>
                  实发工资总计<span className="value"> {shouldMoney}元</span>
                </div>
              )}
            </Title>
          )}
          {this.state.columns.length !== 0 && this.renderTable()}

        </Content>
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          title="导入数据"
          visible={this.state.ifDrawerReport}
          zIndex={11}
          width={600}
          destroyOnClose
          onChange={this.drawerReportOnChange}
          onClose={()=>{ this.setState({ ifDrawerReport:false }); }}
        >
          <Export>
            <div className="item">
              <div className="l">
                导入说明:
              </div>
              <div className="r first">
                <p className="p1">请下载导入模板并根据模板格式填充所需数据。</p>
                <div className="p2">
                  <Icon type="exclamation-circle" className="iconi"/><span
                  style={{marginLeft: "8px"}}>注意：如导入数据前当前表格已有数据，导入数据将替换之前的数据，请谨慎操作！</span>
                  <p onClick={this.downExcel}>下载导入模板</p>
                </div>
              </div>
            </div>
            <div className="item ">
              <div className="l">
                选择导入文件:
              </div>
              <div className="r first">
                {this.renderUploadExcel()}
                {!!uploadResponse && uploadResponse.map((val, key) => {
                  return (
                    <p key={key} className="p2" style={{color: "#F5222E"}}>
                      {`${key + 1}、${val}.`}
                    </p>
                  );
                })}
              </div>
            </div>
            <BottomButton>
              {/* <div>确定</div> */}
              <Button onClick={()=>{ this.setState({ ifDrawerReport:false }); }}>返回</Button>
            </BottomButton>
          </Export>
        </Drawer>

        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          title="报表设置"
          visible={this.state.ifDrawerExport}
          width={600}
          zIndex={11}
          destroyOnClose
          onChange={this.drawerExportOnChange}
          onClose={()=>{ this.setState({ ifDrawerExport:false }); }}
        >
          <Export>
            <div>
              <div className="item">
                <div className="l">
                  修改报表名称:
              </div>
                <Input style={{ width: 294 }}
                  name="reportName"
                  onChange={this.reportSet}
                  value={reportSet.reportName} />
              </div>
              <div className="item">
                <div className="l">
                  修改报表说明:
              </div>
                <Input.TextArea rows={4} style={{ width: 294 }}
                  name="remark"
                  onChange={this.reportSet}
                  value={reportSet.remark} />
              </div>
              <div className="item">
                <div className="l">
                  是否显示薪资总计:
              </div>
                <RadioGroup onChange={this.reportSet}
                  // value={this.state.reportSet.isSumSalary}
                  name="isSumSalary"
                  value={reportSet.isSumSalary}>
                  <Radio value="1">是</Radio>
                  <Radio value="0">否</Radio>
                </RadioGroup>
              </div>
            </div>
            <BottomButton>
              <Button type="primary" onClick={this.enterpriseSalaryComReportUpdateCompanyReport} style={{ marginRight: 8 }}>确定</Button>
              <Button className="normal" onClick={()=>{ this.setState({ ifDrawerExport:false }); }}>返回</Button>
            </BottomButton>
          </Export>
        </Drawer>
      </div>
    );
  }
}

/************************样式************************/

const
  Content = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  padding:22px 24px;
  .searchpanel{
     margin-bottom:16px;
  }
  .split{
    margin:0 8px;
  }
  .value{
    color: #0F71FF;
    margin-left: 4px;
  }
}`;

const
  Opton = style.span`{
  font-size: 12px;
  color: #0F71FF;
  cursor:pointer;
  margin-right:8px;
}`;
const
  Title = style.div`{
    border: 1px solid #D9D9D9;
    border-radius: 4px;
    height:51px;
    line-height:51px;
    padding:0 16px;
    margin-bottom:16px;
}`;
const
  Export = style.div`{
  .title{
    font-size: 18px;
    color: #333333;
    line-height: 21px;
    padding:19px;
    border:1px solid #E9E9E9;
  }
  .item{
     margin-bottom:24px;
     &.small{
     
     }
    .l{
      width:168px;
      display:inline-block;
      text-align:right;
      margin-right:8px;
      vertical-align: top;
    }
    .r{
      width:392px;
      display: inline-block;
      &.first{
        height:96px;
      }
      .p1{
        line-heigth:17px;
        margin-bottom:8px;
      }
      .p2{
        font-size: 12px;
        color: #999999;
        >span{
          width:372px;
        }
        >p{
         margin-top:13px;
         font-size: 14px;
         color: #0F71FF;
         cursor:pointer;
         text-decoration: underline;
        }
      }
    }
  }
}`;
const
  InputChange = style.div`{
  width:211px;
  height:93px;
  padding:16px;
  .btn{
    font-size: 12px;
    float:right;
    border: 1px solid #D9D9D9;
    border-radius: 4px;
    width:44px;
    height:22px;
    line-height:22px;
    margin:9px 0 0 8px;
    text-align:center;
    cursor:pointer;
    &:nth-child(2){
     background: #0F71FF;
     color:#fff;
    }
  }
}`;

const BottomButton = style.div`{
  position: absolute;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 4px 4px;
}`;
