import React, { Component } from 'react';
import axios from 'axios';
import store from 'store';
import style from "styled-components";
import { Tabs, Breadcrumb, Steps, Button, message, Upload, Spin, DatePicker } from 'antd';
import { Link } from "dva/router";
const { TabPane } = Tabs;
const { Step } = Steps;
const { MonthPicker } = DatePicker;
import {
  host
} from '../../services/api';
import moment from 'moment';

export default class ImportSalary extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // grantYears: moment(Date.now()).format('YYYY-MM'),
      grantYears: this.getPreMouth(),
      faileDisabled: 'none', //上传文件失败显示下载失败文件
      failData: '', //上传文件失败返回的数据(链接)
      loading: false
    };
  }
  componentWillMount() {

  }

  getPreMouth() {
    // return moment().format('YYYY-DD');
    // 获取上一个月
    const date = new Date();
    const year = date.getFullYear();
    const mouth = date.getMonth() + 1;
    // return year + '-' + mouth;
    if(mouth > 1) {
      return year + '-' + ((mouth - 1) >= 10?(mouth - 1): '0' + (mouth - 1));
    }else {
      return (year - 1) + '-' + 12;
    }
  }
  //下载
  handleClickLink = () => {
    return (
      <Button
        type="primary"
        onClick={() => {
          axios({
            method: 'get',
            
            url:
            `${host}/task/com/salary/export-salary-template`, //后台请求地址
            headers: {
              access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

            }
          }).then(data => {
            if (!data) {
              return;
            }
            
            let url = data.data.data;
            
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute(
              'download',
              `人员薪酬明细模板.xls`
            );
            document.body.appendChild(link);
            link.click();
          });
        }}
      >
        下载模板
      </Button>
    );
  };
  //选择月份核算
  onPickMonth = (date, dateString) => {
    console.log(date, dateString);
    this.setState(
      {
        grantYears: dateString
      }
    );
  };

  //上传
  handleClickUpload = () => {
    const uploadExcel = {
      name: 'xfile',
      // action: `${host}/system/com-depart/get-import-depart-json`,
      action: `${host}/task/com/salary/import-per-month-salary`,
      headers: {
        authorization: 'Basic c2Fhc3dlYjp3ZWI=',
        access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token']|| sessionStorage.userV5Token,

      },
      showUploadList: false,
      data: {
        month: this.state.grantYears
      }
    };
    const beforeUpload = file => {
      this.setState({
        loading:true
      });
      let ifError = true;
      if (file.name.indexOf('xls') === -1 && file.name.indexOf('xlsx') === -1) {
        this.setState({
          loading:false
        });
        message.error('请上传xls或xlsx文件!');
        ifError = false;
      }
      return ifError;
    };

    //上传文件
    const UploadChange = info => {
      this.setState({
        faileDisabled: 'none',
        // loading: true
      });
      if (info.file.status === 'uploading') {
        return;
      }
      if (info.file.status === 'done') {
        const { data, msg, retType } = info.file.response;
        //"retType":"-1"为错误，data会有相应的路径值
        //"retType":"0"为正确，data为空
        if (retType === '-1') {
          message.error(msg);
          this.setState({
            faileDisabled: 'block',
            failData: data
          });
        } else if (retType === '0') {
          message.success(msg);
        } else {
          message.error(msg);
        }
        this.setState({
          loading: false
        });
      }
    };
    return (
      <div>
        <div
          style={{
            position: 'fixed',
            width: '100%',
            height: '100%',
            top: 0,
            left: 0,
            zIndex: 99999,
            display: this.state.loading ? 'block' : 'none'
          }}
        >
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0, 0, 0, .2)'
            }}
          />
          <Spin
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%'
            }}
            tip="正在导入数据，请稍后..."
          />
        </div>
        <MonthPicker
          style={{marginRight: '20px'}}
          onChange={this.onPickMonth}
          // disabledDate={current => {
          //   return current && current > moment(parseInt(sessionStorage.getItem('requestDate'))).subtract(1, 'month');
          // }}
          placeholder='请选择月份'
          defaultValue={moment().subtract(1, 'month')}
        />
        <Upload
          onChange={UploadChange}
          beforeUpload={beforeUpload}
          {...uploadExcel}
        >
          <Button type="primary">选择上传文件</Button>
        </Upload>
        <div style={{ display: this.state.faileDisabled }}>
          导入失败信息表：
          <a
            type="primary"
            href={this.state.failData}
            style={{ color: 'red', textDecoration: 'underline' }}
            onClick={() => {
              this.setState({
                faileDisabled: 'none'
              });
            }}
          >
            点击下载
          </a>
        </div>
      </div>
    );
  };
  render() {
    return (
      <Box className="import_salary" style={{margin: '16px 0 8px 24px'}}>
        <div>
          <Breadcrumb>
            <Breadcrumb.Item><Link to="/salarymanagement/accounting">薪酬核算</Link></Breadcrumb.Item>
            <Breadcrumb.Item>导入工资数据</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <Tabs defaultActiveKey="1">
          <TabPane tab="导入" key="1">
            <div style={{
              border: '1px solid #e9e9e9',
              borderRadius: '5px',
              padding: '16px 24px',
              marginTop: '16px'
              }}>
              
              <Steps direction="vertical" size="small" current={1}>
                <Step
                  title="下载薪酬信息模板，批量填写薪酬信息"
                  description={this.handleClickLink()}
                />
                <Step
                  title="上传填写好的薪酬信息表"
                  description={this.handleClickUpload()}
                />
              </Steps>
              </div>
          </TabPane>
        </Tabs>
      </Box>
    );
  }
}


const Box = style.div`{
  .import_salary{
    margin:16px 0 8px 24px;
  }
}`;