<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :bodyStyle="bodyStyle"
    @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="选择服务商"
              disabled
              v-decorator="[ 'hlgSubcontractorName', 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="[ 'hlgSubcontractorName', {rules: [{ required: true, message: '请选择服务商' }],initialValue:model.hlgSubcontractorName}]"  :disabled="true"></a-input>
          </template>
        </a-form-item>

        <a-form-item label="金额区间" v-for="(item, index) in hlgTaxRateList" :key="index" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-group>
            <a-row :gutter="24">
              <a-col :span="6">
                <template v-if="index> 0">
                  <a-input-number v-decorator="[ 'hlgTaxRateList['+index+'].startInterval',validatorRules.startInterval]" placeholder="请输入" style="width: 100%"/>
                </template>
                <template v-if="index== 0">
                  <a-input-number v-decorator="[ 'hlgTaxRateList['+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="6" style="padding-left: 0px;">
                <a-input-number v-decorator="[ 'hlgTaxRateList['+index+'].endInterval',validatorRules.endInterval]" placeholder="请输入" style="width: 100%"/>
              </a-col>
              <a-col :span="6" style="padding-left: 0px;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="[ 'hlgTaxRateList['+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">

                <a-row style="float: right">
                  <a-button @click="addRowCustom" icon="plus" style="padding: 0 12px;"></a-button>
                  <a-button @click="delRowCustom(index)" icon="minus" :disabled="index == 0" style="margin-left: 4px;padding: 0 12px;"></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="['taxType',validatorRules.taxType]" :trigger-change="true" @change="changeTaxType"
                             dictCode="tax_type" placeholder="请选择计税方式" style="width: 100%"/>
        </a-form-item>
          
        <a-form-item label="税率提醒" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag type="list" v-decorator="['taxWarnning',validatorRules.taxWarnning]" :trigger-change="true" @change="changeTaxWarnning"
                             dictCode="tax_warnning" placeholder="请选择税率提醒" style="width: 100%"/>
        </a-form-item>


          
        
      </a-form>
    </a-spin>
    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <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-window ref="subcontractorWindow" @ok="modalFormOk"></subcontractor-window>
  </a-modal>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import JDate from '@/components/jeecg/JDate'
  import SubcontractorWindow from '../../hlgplatform/modules/SubcontractorWindow'
  import AFormItem from 'ant-design-vue/es/form/FormItem'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { duplicateCheck } from '@/api/api'
  
  export default {
    name: "HlgTaxModal",
    components: {
      SubcontractorWindow,
      JDate,
      AFormItem,
      JDictSelectTag
    },
    data () {
      return {
        bodyStyle: {
          paddingTop: '20px',
          paddingBottom:'50px',
          height: (window.innerHeight * 0.60) + 'px',
          'overflow-y': 'auto'
        },
        form: this.$form.createForm(this),
        title:"操作",
        width:880,
        visible: false,
        model: {},
        hlgTaxRateList:[{}],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        disableSubmit:false,
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        validatorRules:{
        subcontractorId:{rules: [{ required: true, message: '请输入服务商!' },{
        validator: this.validateCompanyAbbreviation
      }]},
          hlgSubcontractorId:{},
        taxType:{rules: [{ required: true, message: '请输入计税方式!' }]},
        taxWarnning:{rules: [{ required: true, message: '请输入税率提醒!' }]},
        createTime:{rules: [{ required: true, message: '请输入创建时间!' }]},
        createBy:{rules: [{ required: true, message: '请输入创建者!' }]},
          startInterval:{rules: [{ required: true }]},
          endInterval:{rules: [{ required: true }]},
          rate:{rules: [{ required: true }]},
        updateTime:{},
        updateBy:{},
        },
        url: {
          add: "/hlgtax/hlgTax/add",
          edit: "/hlgtax/hlgTax/edit",
        }
     
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form = this.$form.createForm(this)
        this.hlgTaxRateList=[{}]
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'subcontractorId','hlgSubcontractorName','taxType','taxWarnning','createTime','createBy','updateTime','updateBy','hlgTaxRateList','hlgSubcontractorId'))
          this.form.setFieldsValue({ subcontractorId:this.model.subcontractorId!=null? String(this.model.subcontractorId):''})
          this.form.setFieldsValue({ taxType:this.model.taxType!=null? String(this.model.taxType):''})
          this.form.setFieldsValue({ taxWarnning:this.model.taxWarnning!=null? String(this.model.taxWarnning):''})
        })
        this.visible = true;
        this.hlgTaxRateList=this.model.hlgTaxRateList
        if(this.model.id==null){
          this.hlgTaxRateList=[{}]
        }
        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.hlgTaxRateList=this.form.getFieldValue('hlgTaxRateList')
        if (this.hlgTaxRateList.length >0) {
          for (let i = 0; i <this.hlgTaxRateList.length ; i++) {
            console.log(this.hlgTaxRateList[i].startInterval)
            if(this.hlgTaxRateList[i].startInterval==null || this.hlgTaxRateList[i].endInterval==null){
              this.$message.warning('金额区间必填')
              return
            }
            if(this.hlgTaxRateList[i].rate==null){
              this.$message.warning('税率必填')
              return
            }
            if(this.hlgTaxRateList[i].startInterval>=this.hlgTaxRateList[i].endInterval){
              this.$message.warning('金额区间错误')
              return
            }
            if(i==this.hlgTaxRateList.length-1){
              break;
            }
            if(this.hlgTaxRateList[i+1].startInterval!=this.hlgTaxRateList[i].endInterval){
              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.selectedDepartKeys[0]){
              formData.subcontractorId = this.selectedDepartKeys[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,'subcontractorId','taxType','taxWarnning','createTime','createBy','updateTime','updateBy','hlgTaxRateList','hlgSubcontractorId'))
      },
      addRowCustom () {
        this.hlgTaxRateList.push({});
        this.$forceUpdate();
      },
      delRowCustom (index) {
        console.log(index)
        this.hlgTaxRateList.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({ hlgSubcontractorName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
      },

      //校验服务商重复
      validateCompanyAbbreviation(rule, value, callback) {
        console.log(11111,value)
        if(this.selectedDepartKeys[0]){
          value= this.selectedDepartKeys[0];
          console.log(33333,value)
        }
        var params = {
          tableName: 'hlg_tax',
          fieldName: 'subcontractor_id',
          fieldVal: value,
          dataId: this.model.hlgSubcontractorId
        }
        duplicateCheck(params).then((res) => {
          if (res.success) {
            callback()
          } else {
            callback('服务商已存在!')
          }
        })

      },
      changeTaxType(val){
        this.model.taxType = val
      },
      changeTaxWarnning(val) {
        this.model.taxWarnning = val
      },
    }
  }
</script>
<style>
  .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>