<template>
  <a-modal
    centered
    class="addSubsidy-modal"
    :footer="null"
    :maskClosable="false"
    title="新增"
    v-model="isShow"
    @cancel="isShow=false"
    :width="700">
    <div>
      <a-spin :spinning="spinning" tip="Loading...">
        <a-form-model
          id="addSubsidyModal-form"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
        >
          <div class="formList" style="margin-bottom:15px;">
            <a-radio-group id="addSubsidyModal-defaultFlag" v-model="form.defaultFlag" @change="defaultChange">
              <a-radio :value="0" id="addSubsidyModal-defaultFlag0">
                指定客户
              </a-radio>
              <a-radio :value="1" id="addSubsidyModal-defaultFlag1">
                默认
              </a-radio>
            </a-radio-group>
          </div>
          <a-form-model-item label="客户名称" prop="dealerSn" v-if="form.defaultFlag==0">
            <dealerSubareaScopeList style="width:90%;" ref="dealerSubareaScopeList" id="addSubsidyModal-dealerName" @change="custChange" />
          </a-form-model-item>
          <a-form-model-item label="增量补贴（季度）" prop="ruleTarget1">
            <div>
              大于等于<a-input-number
                v-model="form.ruleTarget1"
                :min="1"
                style="width:80px;margin:0 6px;"
                :max="999999"
                id="addSubsidyModal-ruleTarget1"
                :precision="0"
                placeholder="请输入"/>条，每条补贴
              <a-input-number
                v-model="form.ruleValue1"
                :min="0.01"
                id="addSubsidyModal-ruleValue1"
                style="width:80px;margin:0 6px;"
                :max="999999"
                :precision="2"
                placeholder="请输入"/>元
            </div>
            <div>
              大于等于<a-input-number
                v-model="form.ruleTarget2"
                :min="form.ruleTarget1"
                style="width:80px;margin:0 6px;"
                :max="999999"
                id="addSubsidyModal-ruleTarget2"
                :precision="0"
                placeholder="请输入"/>条，每条补贴
              <a-input-number
                v-model="form.ruleValue2"
                :min="form.ruleValue1"
                id="addSubsidyModal-ruleValue2"
                style="width:80px;margin:0 6px;"
                :max="999999"
                :precision="2"
                placeholder="请输入"/>元
            </div>
            <div>
              大于等于<a-input-number
                v-model="form.ruleTarget3"
                :min="form.ruleTarget2"
                style="width:80px;margin:0 6px;"
                :max="999999"
                id="addSubsidyModal-ruleTarget3"
                :precision="0"
                placeholder="请输入"/>条，每条补贴
              <a-input-number
                v-model="form.ruleValue3"
                :min="form.ruleValue2"
                id="addSubsidyModal-ruleValue3"
                style="width:80px;margin:0 6px;"
                :max="999999"
                :precision="2"
                placeholder="请输入"/>元
            </div>
          </a-form-model-item>
          <div class="formList formBoxList" v-if="feeDataList&&feeDataList.length>0">
            <div v-for="item in feeDataList" :key="item.id" style="display:flex;align-items:baseline;">
              <span>{{ item.effectType==1?'当前':'次月' }}增量补贴（{{ pageType==='SUBSIDY_QUARTER_FEE'?'季':'年' }}度）：</span>
              <div>
                <p v-if="item.ruleTarget1">大于等于{{ item.ruleTarget1 }}条，每条补贴{{ item.ruleValue1 }}元;</p>
                <p v-if="item.ruleTarget2">大于等于{{ item.ruleTarget1 }}条，每条补贴{{ item.ruleValue2 }}元;</p>
                <p v-if="item.ruleTarget3">大于等于{{ item.ruleTarget1 }}条，每条补贴{{ item.ruleValue3 }}元;</p>
              </div>
            </div>
          </div>
        </a-form-model>
        <div class="btn-cont">
          <a-button id="addSubsidyModal-cancel" @click="isShow = false" style="margin-right: 15px;">取消</a-button>
          <a-button type="primary" id="addSubsidyModal-save" @click="handleSave">保存</a-button>
        </div>
      </a-spin>
    </div>
  </a-modal>
</template>

<script>
// 组件
import { VSelect } from '@/components'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
// 接口
import { subsidyRuleSave, createSubsidyRule, getSubsidyRuleList } from '@/api/subsidyRule'
export default {
  name: 'AddSubsidyModal',
  components: { VSelect, dealerSubareaScopeList },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    pageType: { //  页面类型
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 17 }
      },
      // 提交数据
      form: {
        defaultFlag: 0, // 0指定客户  1默认
        dealerSn: undefined, // 客户名称
        ruleTarget1: undefined, // 增量补贴
        ruleValue1: undefined,
        ruleTarget2: undefined,
        ruleValue2: undefined,
        ruleTarget3: undefined,
        ruleValue3: undefined
      },
      // 必填项判断
      rules: {
        dealerSn: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
        ruleTarget1: [{ required: true, message: '增量补贴不能为空', trigger: 'blur' }]
      },
      feeDataList: null
    }
  },
  methods: {
    // 客户名称 change
    custChange (val) {
      if (val && val.key) {
        this.form.dealerSn = val.key
        this.getHistoryData({ dealerSn: val.key, subsidyQueryStatus: 'NOT_FINISH', ruleType: this.pageType })
      } else {
        this.feeDataList = null
      }
    },
    // 0指定客户  1默认客户  change
    defaultChange (e) {
      this.form.defaultFlag = e.target.value
      this.form.dealerSn = undefined
      if (e.target.value == '1') {
        this.getHistoryData({ defaultFlag: 1, subsidyQueryStatus: 'NOT_FINISH', ruleType: this.pageType })
      } else {
        this.feeDataList = null
      }
    },
    // 获取当月/次月  历史数据值
    getHistoryData (ajaxData) {
      this.spinning = true
      getSubsidyRuleList(ajaxData).then(res => {
        if (res.status == 200) {
          this.feeDataList = res.data
        } else {
          this.feeDataList = null
        }
        this.spinning = false
      })
    },
    // 保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 为空判断
          const newForm = JSON.parse(JSON.stringify(_this.form))
          delete newForm.defaultFlag
          delete newForm.dealerSn
          const flag = _this.isValid(newForm)
          if (!flag) {
            _this.$message.error('季度增量补贴【条数】与【补贴】不符合填写规则！')
            return
          }

          _this.form.ruleType = _this.pageType
          _this.spinning = true
          subsidyRuleSave(_this.form).then(res => {
            if (res.status == 200) {
              if (!res.data) {
                _this.isShow = false
                _this.$message.success(res.message)
                _this.$emit('ok')
              } else {
                _this.openTip(res.data)
              }
            }
            _this.spinning = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 为空判断
    isValid (obj) {
      const { ruleTarget1, ruleValue1, ruleTarget2, ruleValue2, ruleTarget3, ruleValue3 } = obj

      // 检查第一阶梯是否填写
      if (ruleTarget1 === undefined || ruleValue1 === undefined || typeof ruleValue1 !== 'number') {
        return false
      }

      // 如果第三阶梯存在，检查第二阶梯是否存在以及值是否正确
      if (ruleTarget3 !== undefined || ruleValue3 !== undefined) {
        if (ruleTarget2 === undefined || ruleValue2 === undefined || typeof ruleValue2 !== 'number') {
          return false
        }
        if (ruleValue1 >= ruleValue2 || (ruleValue3 !== undefined && ruleValue2 >= ruleValue3) || ruleTarget1 >= ruleTarget2 || (ruleTarget3 !== undefined && ruleTarget2 >= ruleTarget3)) {
          return false
        }
      }

      // 如果只有第二阶梯存在（没有第三阶梯），检查值是否正确
      if (ruleTarget2 !== undefined && ruleValue2 !== undefined && (ruleTarget3 === undefined && ruleValue3 === undefined)) {
        if (ruleValue1 >= ruleValue2 || ruleTarget1 >= ruleTarget2) {
          return false
        }
      }
      // 所有条件都满足，返回true
      return true
    },
    openTip (code) {
      const _this = this
      if (code === 'WAIT') {
        this.$confirm({
          title: '提示',
          content: '将重新生成新的' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季' : '年') + '度补贴，并结束当前' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季' : '年') + '度增量补贴。',
          centered: true,
          onOk () {
            createSubsidyRule(_this.form).then(res => {
              if (res.status == 200) {
                _this.isShow = false
                _this.$message.success(res.message)
                _this.$emit('ok')
              }
            })
          }
        })
      } else {
        this.$info({
          title: '提示',
          content: '已存在【启用中】的' + (_this.pageType === 'SUBSIDY_QUARTER_FEE' ? '季' : '年') + '度增量补贴',
          centered: true,
          onOk () {
            console.log('知道了')
          }
        })
      }
    },
    // 重置
    resetFormData () {
      this.form.defaultFlag = 0
      this.form.dealerSn = undefined
      this.form.ruleTarget1 = undefined
      this.form.ruleValue1 = undefined
      this.form.ruleTarget2 = undefined
      this.form.ruleValue2 = undefined
      this.form.ruleTarget3 = undefined
      this.form.ruleValue3 = undefined
      if (this.form.defaultFlag == 0) {
        this.$refs.dealerSubareaScopeList.resetForm()
      }
      this.feeDataList = null
      this.$refs.ruleForm.resetFields()
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetFormData()
      }
    }
  }
}
</script>

<style lang="less">
  .addSubsidy-modal{
    .formList{
      margin-left:60px;
    }
    .formBoxList{
      div{
        margin-bottom:5px;
      }
    }
    .ant-modal-body {
      padding: 40px 40px 24px;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 30px;
    }
  }
</style>
