<template>
    <div class="reply" ref = "replyModal">
      <a-modal
        title="生成工资单"
        width="30%"
        :visible="visible"
        :confirmLoading="loading"
        :getContainer ='()=>$refs.replyModal'
        @cancel="handleCancel"
        destroyOnClose
        :closable="!loading"
        :maskClosable="!loading"
       >
            <template #footer>
                <a-button  @click="handleCancel" :loading = "loading">取消</a-button>
                <a-button  @click="handleOk" type="primary" style="margin-left: 8px;" :loading = "loading">确认</a-button>
            </template>
            <div class="table-page-search-wrapper">
                <a-form-model layout="inline" ref="form" :model="formState" :rules="validatorRules">
                    <a-row :gutter="24">
                        <a-col :md="24">
                            <a-form-model-item label="类型"  prop="type"  :labelCol="{offset: 2}">
                                <a-select  v-model="formState.type" @change="changeType">
                                    <a-select-option value="加班工资单">加班工资单</a-select-option>
                                    <a-select-option value="年休工资单">年休工资单</a-select-option>
                                    <a-select-option value="月度工资单">月度工资单</a-select-option>
                                </a-select>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" >
                            <a-form-model-item label="计算月份"  prop="yearWithMonth" :labelCol="{offset:1}" v-if="formState.type=='加班工资单'||formState.type=='月度工资单'">
                                <a-month-picker placeholder="请选择" v-model="formState.yearWithMonth"  style="width:100% !important"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" >
                            <a-form-model-item label="计算年份"  prop="yearWith" :labelCol="{offset: 1}" v-if="formState.type=='年休工资单'">
                                <a-date-picker placeholder="请选择" :open="isopen" mode="year" v-model="formState.yearWith" format="YYYY" style="width:100% !important" @openChange="changeopen" @panelChange="handlePanelChange1"/>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" >
                            <a-form-model-item label="加班月份区间"  prop="DateTime" v-if="formState.type=='加班工资单'">
                                <a-range-picker
                                    style="width: 100% !important"
                                    v-model="formState.DateTime"
                                    format="YYYY-MM"
                                    valueFormat="YYYY-MM"
                                    :mode="mode2"
                                    :open="open"
                                    :placeholder="['开始时间', '结束时间']"
                                    @panelChange="handlePanelChange2"
                                    @openChange="onDateChange"
                                    @change="changeData"
                                    />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </div>
      </a-modal>
      <a-modal
        width="30%"
        title="请确认"
        :visible="visibleOk"
        @ok="handleOkPayroll"
        @cancel="handleCancelPayroll"
        :getContainer ='()=>$refs.replyModal'
        >
            <p>{{ ModalText }}</p>
    </a-modal>
    </div>
</template>
<script>
    
      import moment from 'moment'
      import pick from 'lodash.pick'
      import { FormTypes } from '@/utils/JEditableTableUtil'
      import { putAction,getAction,postAction,downFile } from '@/api/manage'
      export default {
        name: 'uploadModal',
        components: {
            moment,
        },
        data() {
          return {
              formState:{
                type:'月度工资单',
                yearWithMonth:moment().subtract(1, 'months'),
                DateTime:[],
                yearWith:''
              },
              open: false,
              isopen:false,
              dataSource: [{}],
              mode2: ['month', 'month'],
              visible:false,
              visibleOk:false,
              ModalText:'',
              loading:false,    
              validatorRules: {
                type: [{required: true, message: '请选择!' }],
                yearWithMonth: [{required: true, message: '请选择!' }],
                DateTime: [{required: true, message: '请选择!',trigger: 'change' }],
                yearWith: [{required: true, message: '请选择!',trigger: 'change' }],
              },           
          }
        },
        created(){
        },
        watch: {
        },
        methods: {
            handleCancel(){
                this.visible = false
                this.formState={
                    type:'月度工资单',
                    yearWithMonth:moment().subtract(1, 'months'),
                    DateTime:[],
                    yearWith:''
                }
                // this.DateTime = []
            },
            changeType(data){
                if(data=='月度工资单'){
                    this.formState={
                        type:'月度工资单',
                        yearWithMonth:moment().subtract(1, 'months')
                    }
                }else if(data=='加班工资单'){
                    this.formState={
                        type:'加班工资单',
                        yearWithMonth:moment().subtract(1, 'months'),
                        DateTime:[]
                    }
                }else if(data=='年休工资单'){
                    this.formState={
                        type:'年休工资单',
                        yearWith:moment().subtract(1, 'year')
                    }
                }
            },
            handleOk(){
                this.$refs.form.validate((valid,err) => {
                    if (valid) {
                        if(this.formState.type=='加班工资单'){
                            this.formState.beginMonth = moment(this.formState.DateTime[0]).format('YYYY-MM')
                            this.formState.endMonth = moment(this.formState.DateTime[1]).format('YYYY-MM')
                            delete this.formState.DateTime
                        }
                        if(this.formState.type=='加班工资单'||this.formState.type=='月度工资单'){
                            this.formState.yearWithMonth = moment(this.formState.yearWithMonth).format('YYYY-MM')
                        }
                        if(this.formState.type=='年休工资单'){
                            this.formState.yearWith = moment(this.formState.yearWith).format('YYYY')
                        }
                        this.loading = true
                        let that = this;
                        postAction('/salary/salaryManagement/generatePayrollBefore',this.formState).then((res) => {
                            if (res.success) {
                               this.generatePayroll(this.formState)
                            } else {
                                this.ModalText = res.message
                                this.visibleOk = true
                            }
                        }).finally(() => {
                            this.loading = false
                        }) 
                    }
                })

            },
            handleOkPayroll(){
                this.ModalText = ''
                this.visibleOk = false
                this.generatePayroll(this.formState)
            },
            handleCancelPayroll(){
                this.ModalText = ''
                this.visibleOk = false
            },
            generatePayroll(data){
                this.loading = true
                let that = this;
                postAction('/salary/salaryManagement/generatePayroll',data).then((res) => {
                    if (res.success) {
                        if(res.data&&res.data.ZZ){
                             that.handleDownload(res.data.ZZ,that.formState.type,"正织",data);
                        }
                        if(res.data&&res.data.MFY){
                             that.handleDownload(res.data.MFY,that.formState.type,"马菲羊",data);
                        }
                        if(res.data&&res.data.NBSY){
                            that.handleDownload(res.data.NBSY,that.formState.type,"宁波森语",data);
                        } 
                        this.$message.success(res.message);
                        this.handleCancel()
                        this.$emit('ok')
                    } else {
                        this.$message.error(res.message);
                    }
                }).finally(() => {
                    this.loading = false
                })
            },
            handleDownload(id,type,name,datas){
              downFile('/salary/salaryManagement/exportXls2',{id:id,type:type}).then(data => {
                
                this.$message.success(name+type+"数据导出中，请稍等");
                
                if (!data) {
                  this.$message.warning('文件下载失败')
                  return
                }
                
                let datePar = "";
                if(type == '年休工资单'){
                  datePar = datas.yearWith;
                  // datePar = moment(data.yearWith).format('YYYY');
                }else{
                  datePar = datas.yearWithMonth;
                  // datePar = moment(data.yearWithMonth).format('YYYY-MM');
                }
                
                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), name+datePar+type + '.xls')
                } else {
                  let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
                  let link = document.createElement('a')
                  link.style.display = 'none'
                  link.href = url
                  link.setAttribute('download',  name+datePar+type+'.xls')
                  document.body.appendChild(link)
                  link.click()
                  document.body.removeChild(link) // 下载完成移除元素
                  window.URL.revokeObjectURL(url) // 释放掉blob对象
                }
              })
            },
            changeData(value){
                this.formState.DateTime = value
            },
            onDateChange(status) {
                if(status){
                    this.open = true;
                }else{
                    this.open = false
                 }
            },
            handlePanelChange2(value,mode){
                if (this.formState.DateTime[1] && this.formState.DateTime[1]._d != value[1]._d) {
                    this.open = false;
                    this.$refs.form.clearValidate();
                }
                this.formState.DateTime = value
                this.mode2 = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]];
            },
            handlePanelChange1(value){
                this.isopen = false
                this.formState.yearWith =value

            },
            changeopen(status){
                if(status){
                    this.isopen =  true
                }
            }
        }
    }
    </script>
    
    <style scoped lang="less">
    /deep/ .nresume .ant-input{
      height: 100px !important;
    }

    /deep/ .ant-select{
      width: 100%;
    }
    .form-table-heard:before {
          content: '*';
          color: red;
    }
    /deep/ .ant-calendar-picker{
      width: 113px !important;
    }
    /deep/.ant-modal-root>.ant-modal-wrap>.ant-modal {
      min-width: 0 !important;
    }
    </style>