<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :bodyStyle="bodyStyle"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    cancelText="关闭"
    :footer="null">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <template v-if="!model.id">
            <a-input-search
              placeholder="选择服务商"
              readOnly
              v-decorator="[ 'hlwSubcontractorName', validatorRules.subcontractorId]"
              @search="onSearch">
              <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
            </a-input-search>
          </template>
          <template v-else>
            <a-input v-decorator="[ 'hlwSubcontractorName', {rules: [{ required: true, message: '请选择服务商' }],initialValue:model.hlwSubcontractorName}]"  :disabled="true"></a-input>
          </template>
        </a-form-item>

        <a-form-item label="金额区间" v-for="(item, index) in hlwTaxRateList" :key="index" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-group>
            <a-row :gutter="24">
              <a-col :span="4">
                <template v-if="index> 0">
                  <a-input-number v-decorator="[ 'hlwTaxRateList['+index+'].startInterval',validatorRules.startInterval]" placeholder="请输入" style="width: 100%"/>
                </template>
                <template v-if="index== 0">
                  <a-input-number v-decorator="[ 'hlwTaxRateList['+index+'].startInterval',{'initialValue':0, rules: [{ required: true }]}]" :disabled="true" placeholder="请输入" style="width: 100%"/>
                </template>
              </a-col>
              <a-col :span="1" style="padding-left: 0px;padding-right: 0px;">
                ~
              </a-col>
              <a-col :span="4" style="padding-left: 0px;">
                <a-input-number v-decorator="[ 'hlwTaxRateList['+index+'].endInterval',validatorRules.endInterval]" placeholder="请输入" style="width: 100%"/>
              </a-col>
              <a-col :span="5" style="padding-left: 8px;padding-right: 0px;">
                <a-row>
                  <a-col :span="8">
                    <span class="ant-form-item-required" style="vertical-align: middle;">税率:</span>
                  </a-col>
                  <a-col :span="16">
                    <a-input-number v-decorator="[ 'hlwTaxRateList['+index+'].rate',validatorRules.rate]" :min="0" :max="99.99"  :precision="2"  :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" placeholder="请输入税率" style="width: 100%"/>
                  </a-col>
                </a-row>
              </a-col>


              <a-col :span="5" style="padding-left: 10px;padding-right: 0px;">
                <a-row>
                  <a-col :span="10">
                    <span class="ant-form-item-required" style="vertical-align: middle;">速算值:</span>
                  </a-col>
                  <a-col :span="14">
                    <a-input-number v-decorator="[ 'hlwTaxRateList['+index+'].calculationValue',validatorRules.calculationValue]" :min="0"     placeholder="请输入速算值" style="width: 100%"/>
                  </a-col>
                </a-row>
              </a-col>


              <a-col :span="5">

                <a-row style="float: right;">
                  <a-button @click="addRowCustom" icon="plus" ></a-button>
                  <a-button @click="delRowCustom(index)" icon="minus" :disabled="index == 0" style="margin-left: 4px;"></a-button>
                </a-row>

              </a-col>
            </a-row>
          </a-input-group>
        </a-form-item>



        <a-form-item label="税率提醒" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" v-decorator="['taxWarning',validatorRules.taxWarning]" :trigger-change="true" @change="changeTaxWarning"
                             dictCode="tax_warning" placeholder="请选择税率提醒" style="width: 100%"/>
        </a-form-item>

        <a-form-item label="累计方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" v-decorator="['accumulationType',validatorRules.accumulationType]" :trigger-change="true" @change="changeAccumulationType"
                             dictCode="accumulation_type" placeholder="请选择累计方式" style="width: 100%"/>
        </a-form-item>


        <a-form-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择开始时间" v-decorator="[ 'startDate', validatorRules.startDate]" :trigger-change="true" style="width: 100%" :readOnly="disableSubmit1"/>
        </a-form-item>

        <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-date placeholder="请选择结束时间" v-decorator="[ 'endDate', validatorRules.endDate]" :trigger-change="true" style="width: 100%" :readOnly="disableSubmit2"/>
        </a-form-item>

      </a-form>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!model.id">
      <a-button class="ant-btn"  @click="handleCancel">取消</a-button>
      <a-button class="ant-btn ant-btn-primary" style="margin-left: 8px"  @click="handleOk">确定</a-button>
    </div>
    <subcontractor-select-window ref="subcontractorWindow" @ok="modalFormOk"></subcontractor-select-window>
  </j-modal>
</template>

<script>

  import { httpAction, getAction  } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JDate from '@/components/jeecg/JDate'
  import AFormItem from 'ant-design-vue/es/form/FormItem'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { duplicateCheck } from '@/api/api'
  import SubcontractorSelectWindow from '../../hlwsubcontractor/modules/SubcontractorSelectWindow'


  export default {
    name: "HlwTaxModal",
    components: {
      SubcontractorSelectWindow,
      JDate,
      AFormItem,
      JDictSelectTag
    },
    data () {
      return {
        disableSubmit1: false,
        disableSubmit2:false,
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.60) + 'px',
          'overflow-y': 'auto'
        },
        form: this.$form.createForm(this),
        title:"操作",
        width:1200,
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        disableSubmit:false,
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        hlwTaxRateList:[{}],
        validatorRules: {
          subcontractorId:{rules: [{ required: true, message: '请选择服务商!' }]},
          taxWarning: {
            rules: [
              { required: true, message: '请输入税率提醒'},
            ]
          },
          accumulationType: {
            rules: [
              { required: true, message: '请输入累计方式'},
            ]
          },
          startDate: {
            rules: [
              { required: true, message: '请输入开始时间!'},
            ]
          },
          endDate: {
            rules: [
              { required: true, message: '请输入结束时间!'},
            ]
          },
          createTime: {
            rules: [
              { required: true, message: '请输入创建时间!'},
            ]
          },
          createBy: {
            rules: [
              { required: true, message: '请输入创建者!'},
            ]
          },
        },
        url: {
          add: "/wisdom/hlwTax/add",
          edit: "/wisdom/hlwTax/edit",
          taxList: "/wisdom/hlwTax/taxList",
        }
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form = this.$form.createForm(this)
        this.hlwTaxRateList=[{}]
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.disableSubmit1=false
        this.disableSubmit2=false
        if(this.model.id){
          this.disableSubmit1=true
          this.disableSubmit2=true
        }
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'subcontracctorId','taxWarning','accumulationType','startDate','endDate','createTime','createBy','updateTime','updateBy','hlwTaxRateList','hlwSubcontractorName'))
          this.form.setFieldsValue({ subcontractorId:this.model.subcontractorId!=null? String(this.model.subcontractorId):''})
          this.form.setFieldsValue({ taxWarning:this.model.taxWarning!=null? String(this.model.taxWarning):''})
          this.form.setFieldsValue({ accumulationType:this.model.accumulationType!=null? String(this.model.accumulationType):''})
        })
        this.hlwTaxRateList=this.model.hlwTaxRateList
        if(this.model.id==null){
          this.hlwTaxRateList=[{}]
        }
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        if(this.model.subcontractorId){
          this.checkedDepartKeys.push(this.model.subcontractorId);
        }
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
      },
      handleOk () {
        this.hlwTaxRateList=this.form.getFieldValue('hlwTaxRateList')
        if (this.hlwTaxRateList.length >0) {
          for (let i = 0; i <this.hlwTaxRateList.length ; i++) {
            console.log(this.hlwTaxRateList[i].startInterval)
            if(this.hlwTaxRateList[i].startInterval==null || this.hlwTaxRateList[i].endInterval==null){
              this.$message.warning('金额区间必填')
              return
            }
            if(this.hlwTaxRateList[i].rate==null){
              this.$message.warning('税率必填')
              return
            }
            if(this.hlwTaxRateList[i].calculationValue==null){
              this.$message.warning('速算值必填')
              return
            }
            if(this.hlwTaxRateList[i].startInterval>=this.hlwTaxRateList[i].endInterval){
              this.$message.warning('金额区间错误')
              return
            }
            if(i==this.hlwTaxRateList.length-1){
              break;
            }
            if(this.hlwTaxRateList[i+1].startInterval!=this.hlwTaxRateList[i].endInterval){
              this.$message.warning('金额区间错误')
              return
            }


          }
        }
        this.endDate=this.form.getFieldValue('endDate')
        this.startDate=this.form.getFieldValue('startDate')
        console.log(111,this.startDate)
        if(new Date(this.endDate).getTime()<=new Date(this.startDate).getTime()){
          this.$message.warning('结束时间必须大于开始时间')
          return
        }
        if(new Date(this.endDate).getTime()<new Date().getTime()){
          this.$message.warning('结束时间不能早于今天')
          return
        }
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            if(this.checkedDepartKeys[0]){
              console.log(1111111,this.checkedDepartKeys[0])
              formData.subcontractorId = this.checkedDepartKeys[0];
            }
            console.log("表单提交数据",formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
         
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'subcontracctorId','taxWarning','accumulationType','startDate','endDate','createTime','createBy','updateTime','updateBy'))
      },
      addRowCustom () {
        this.hlwTaxRateList.push({});
        this.$forceUpdate();
      },
      delRowCustom (index) {
        console.log(index)
        this.hlwTaxRateList.splice(index,1);
        this.$forceUpdate();
      },

      //搜索服务商
      onSearch(){
        this.$refs.subcontractorWindow.add(this.checkedDepartKeys);
      },
      // 获取用户选择服务商弹提交的返回数据
      modalFormOk (formData) {
        this.selectedDepartKeys = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ hlwSubcontractorName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
        let params = {subcontractorId:this.selectedDepartKeys[0]}
        getAction(this.url.taxList,params).then((res)=>{
          if(res.success){
            this.form.setFieldsValue({ startDate:this.formatDate(new Date(new Date(res.result.endDate).getTime()+3600*24*1000))})
            this.disableSubmit1=true
          }
        })
      },


   formatDate(now) {
    var year=now.getFullYear();
    var month=now.getMonth()+1;
    var date=now.getDate();
    return year+"-"+month+"-"+date;
  },

      changeAccumulationType(val){
        this.model.accumulationType = val
      },
      changeTaxWarning(val) {
        this.model.taxWarning = val
      },



      
    }
  }
</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>