import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Tabs, Alert, Form, Button, DatePicker, Select } from 'antd';
import './less/medical.less';
import PTable from '../../../components/Pro/PTable';
import * as request from '../../../utils/request.js';
import * as ajax from '../../../services/api'; //
import store from 'store';
import axios from 'axios';

const { MonthPicker } = DatePicker;
const { Option } = Select;
const monthFormat = 'YYYY-MM';
const { TabPane } = Tabs;

@connect(state => ({
  global: state.global
}))
@Form.create()

/**
 * 医社保记录查询
 */
export default class MedicalBasic extends Component {
  constructor(props, context) {
    super(props, context);
    // const curDate = new Date();
    // const preDate = new Date(curDate.getTime() - (30 * 24 * 60 * 60 * 1000)); //前一天
    this.state = {
      forceUpdate: false,
      pay: false, //是否设置缴交比例
      payMsg: '',
      comTotalPayAmount: '', //企业缴费总计
      perTotalPayAmount: '', //个人缴费总计
      totalPayAmount: '', //总缴费
      pageParm: {
        paySituation: '3', //缴交情况
        pageSize: '10',
        payPeriod: this.getMonth(),
        pageNumber: '1'
      },
      payPeriod: this.getMonth(), //时间默认值
      paySituation: '3' //缴交情况默认值
    };
  }

  getMonth = () => {
    const nowdays = new Date();
    let year = nowdays.getFullYear();
    let month = nowdays.getMonth();
    if (month === 0) {
      month = 12;
      year--;
    }
    if (month < 10) {
      month = '0' + month;
    }
    const yearMon = year + '-' + month; //上个月的第一天  + "-" + "01"
    return yearMon;
  };

  //render之后调用
  componentDidMount() {
    this.ajaxGetStaticInfo();
    this.toSetScheme();
  }

  //声明函数 时间选择
  onChangeTime = (date, dateString) => {
    console.log('dateString' + dateString);
    this.setState({ payPeriod: dateString });
  };

  //声明函数 ajax获取数据，搜索按钮
  getRecList = () => {
    this.ajaxGetStaticInfo(); //获取统计数据
    const pageParm = { ...this.state.pageParm };
    pageParm.paySituation = this.state.paySituation;
    pageParm.payPeriod = this.state.payPeriod;
    console.log('>>>>>>>>>>>>>>>>>>>', pageParm);
    this.setState({ pageParm, forceUpdate: true }, () => {
      this.setState({ forceUpdate: false });
    });
  };

  //头部提醒
  setPay = () => {
    if (this.state.pay === 0) {
      return (
        <div>
          <Alert
            message={
              <div>
                <span>{this.state.payMsg}</span>
                <a
                  type='primary'
                  onClick={() => {
                    this.props.history.push('/salarymanagement/proportion');
                  }}
                >
                  去设置
                </a>
              </div>
            }
            type='warning'
            showIcon
          />
        </div>
      );
    } else if (this.state.pay === 1) {
      return (
        <div>
          <Alert
            message={
              <div>
                <span>{this.state.payMsg}</span>
                <a
                  type='primary'
                  onClick={() => {
                    this.props.history.push('/salarymanagement/proportion');
                  }}
                >
                  去设置
                </a>
              </div>
            }
            type='warning'
            showIcon
          />
        </div>
      );
    } else {
      return <div className='medical-head' />;
    } //2表示不需要提示
  };

  //ajax 获取统计数据
  ajaxGetStaticInfo = () => {
    ajax
      .statHisRecList({
        comId: this.props.global.companyInfo.comId,
        payPeriod: this.state.payPeriod
      })
      .then(data => {
        console.log('医社保记录统计', data.data);
        if (data.data) {
          this.setState({
            totalPayAmount: data.data.totalPayAmount,
            comTotalPayAmount: data.data.comTotalPayAmount,
            perTotalPayAmount: data.data.perTotalPayAmount
          });
        } else {
          this.setState({
            totalPayAmount: 0,
            comTotalPayAmount: 0,
            perTotalPayAmount: 0
          });
        }
      });
  };

  //缴交情况
  handleChangeCondition = value => {
    console.log(`selected ${value}`);
    this.setState({ paySituation: value });
  };

  //声明函数 导出excel
  exportList = () => {
    ajax
      .exportHisRecList({
        comId: this.props.global.companyInfo.comId,
        payPeriod: this.state.pageParm.payPeriod
      })
      .then(
        data => {
          console.log('导出成功', data);
        },
        err => {
          console.log('导出失败', err);
        }
      );
  };

  //提示用户去完成方案的设置
  toSetScheme = () => {
    ajax
      .promptUserToSetScheme({ comId: this.props.global.companyInfo.comId })
      .then(
        data => {
          console.log('提示用户去完成方案的设置' + data.data);
          this.setState({
            pay: data.data,
            payMsg: data.msg
          });
        },
        err => {
          console.log('提示用户去完成方案的设置err', err);
        }
      );
  };

  //PTable 回调函数
  dateTableChange = data => {
    console.log('PTable 回调函数', data);
  };
  handleClickLink = () => {



    axios({
      method: 'get',

      url:
        request.getHostByPath('/enterprise') +
        '/enterprise/ins/medical-social-rec/export-his-rec-list?comId=' +
        this.props.global.companyInfo.comId +
        '&payPeriod=' +
        this.state.pageParm.payPeriod, //后台请求地址
      headers: {
        access_token: store.get('saas')['access_token'],
        Accesstoken: store.get('saas')['access_token'] || sessionStorage.userV5Token,

      },
      responseType: "blob",

    }).then(data => {
      if (!data) {
        return;
      }

      // 假设response是从后端获取的文件流
      // 创建Blob对象
      const blob = new Blob([data.data], { type: 'application/vnd.ms-excel;charset=utf-8' });

      // 创建一个虚拟的URL，用于下载
      const url = window.URL.createObjectURL(blob);

      // 创建一个<a>元素，设置其href属性为虚拟URL，触发下载
      const link = document.createElement('a');
      link.href = url;
      link.download = '五险一金.xls'; // 设置下载文件的名称
      document.body.appendChild(link);
      link.click();

      // 清理创建的URL对象
      window.URL.revokeObjectURL(url);


    });
  };
  // 表格渲染
  renderOrderList = () => {
    // const pageInitStudent = {
    //   defaultPageSize: 10,
    //   showQuickJumper: true,
    //   pageSizeOptions: ["5", "10", "15", "20", "25"],
    //   showSizeChanger: true,
    //   showTotal: () => { return '共 ' + this.state.total + ' 条数据';  }
    // };
    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        fixed: 'left'
      },
      {
        title: '身份证号',
        dataIndex: 'idCardNo',
        key: 'idCardNo',
        width: 180,
        fixed: 'left'
      },
      {
        title: '企业缴交',
        children: [
          {
            title: '养老保险',
            dataIndex: 'pensionComPayAmount',
            key: 'pensionComPayAmount'
          },
          {
            title: '医疗保险',
            dataIndex: 'medicalComPayAmount',
            key: 'medicalComPayAmount'
          },
          {
            title: '失业保险',
            dataIndex: 'unemploymentComPayAmount',
            key: 'unemploymentComPayAmount'
          },
          {
            title: '工伤保险',
            dataIndex: 'injuryComPayAmount',
            key: 'injuryComPayAmount'
          },
          {
            title: '生育保险',
            dataIndex: 'birthComPayAmount',
            key: 'birthComPayAmount'
          },
          {
            title: '公积金',
            dataIndex: 'fundComPayAmount',
            key: 'fundComPayAmount'
          }
        ]
      },
      {
        title: '个人缴交',
        children: [
          {
            title: '养老保险',
            dataIndex: 'pensionPerPayAmount',
            key: 'pensionPerPayAmount'
          },
          {
            title: '医疗保险',
            dataIndex: 'medicalPerPayAmount',
            key: 'medicalPerPayAmount'
          },
          {
            title: '失业保险',
            dataIndex: 'unemploymentPerPayAmount',
            key: 'unemploymentPerPayAmount'
          },
          {
            title: '工商保险',
            dataIndex: 'injuryPerPayAmount',
            key: 'injuryPerPayAmount'
          },
          {
            title: '生育保险',
            dataIndex: 'birthPerPayAmount',
            key: 'birthPerPayAmount'
          },
          {
            title: '公积金',
            dataIndex: 'fundPerPayAmount',
            key: 'fundPerPayAmount'
          }
        ]
      },
      {
        title: '合计',
        dataIndex: 'totalPayAmount',
        key: 'totalPayAmount',
        width: 130,
        fixed: 'right'
      }
    ];

    return (
      <PTable
        columns={columns}
        url='getHisRecListPage'
        pageParm={this.state.pageParm}
        dateChange={this.dateTableChange}
        // scroll={{ x:'200%',}}
        scroll={{ x: 1800 }}
        forceUpdate={this.state.forceUpdate}
        showTotal
        bordered
      />
    );
  };

  render() {
    return (
      <div className='medical'>
        <Tabs>
          <TabPane tab='五险一金设置' key='1' />
        </Tabs>
        <Alert
          message={
            <div style={{ color: '#f90' }}>
              <div>
                1、请为每个需要核算薪酬的员工设置五险一金的基数及比例，系统每月1号会自动生成该月份每个员工五险一金的缴纳金额；
              </div>
              <div>
                2、每月生成的五险一金缴纳金额会关联到本月薪酬核算的薪酬数据中，若未设置五险一金，则薪酬核算无法获取相应金额数据。
              </div>
            </div>
          }
          type='warning'
          showIcon
          style={{ marginBottom: '15px' }}
        />
        {this.setPay()}

        <div className='medical-chearch'>
          <label>
            缴费年月：
            <MonthPicker
              format={monthFormat}
              defaultValue={moment(this.state.pageParm.payPeriod, monthFormat)}
              onChange={this.onChangeTime}
              placeholder='请选择年月'
              allowClear={false}
            />
          </label>
          <label style={{ marginLeft: '16px' }}>缴交情况：</label>
          <Select
            showSearch
            style={{ width: 214 }}
            optionFilterProp='children'
            placeholder='请选择'
            onChange={this.handleChangeCondition}
            defaultValue={this.state.paySituation}
          >
            <Option value='1'>未缴费人员</Option>
            <Option value='2'>已缴费人员</Option>
            <Option value='3'>全部人员</Option>
          </Select>
          <Button
            style={{ marginLeft: 16 }}
            type='primary'
            onClick={this.getRecList}
          >
            搜索
          </Button>
        </div>
        <div className='medical-content'>
          <span>{this.state.pageParm.payPeriod}</span>|<span>应缴交总计</span>
          <span className='span-blue'>{this.state.totalPayAmount}元</span>|
          <span>企业缴交总金额</span>
          <span className='span-blue'>{this.state.comTotalPayAmount}元</span>|
          <span>个人缴交总金额</span>
          <span className='span-blue'>{this.state.perTotalPayAmount}元</span>
        </div>
        <div className='medical-link' style={{ marginBottom: '10px' }}>
          <Button
            type='primary'
            style={{ marginRight: '8px' }}
            onClick={() =>
              this.handleClickLink()
            }
          >
            导出excel
          </Button>
          {/* {console.log(request.getHostByPath('/enterprise') + '/enterprise/ins/medical-social-rec/export-his-rec-list?comId=' + this.state.pageParm.comId + '&payPeriod=' + this.state.pageParm.payPeriod)} */}
          <Button
            onClick={() => {
              this.props.history.push('/salarymanagement/proportion');
            }}
          >
            缴费比例管理
          </Button>
        </div>
        {this.renderOrderList()}
      </div>
    );
  }
}
