<template>
  <div>
    <a-modal
      class="modalBox"
      :title="titleText"
      v-model="isshow"
      :footer="null"
      @cancle="cancel"
      :width="800"
      :centered="true">
      <a-form :form="form" @submit="handleSubmit">
        <!-- 规则名称 -->
        <a-form-item label="规则名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
          <a-input
            placeholder="请输入规则名称(最多30个字符)"
            allowClear
            :maxLength="30"
            id="addSetModal-name"
            v-decorator="['formData.name', {
              initialValue: formData.name,getValueFromEvent: $filterEmpty,
              rules: [{ required: true, message: '请输入规则名称(最多30个字符)!' }] }]" />
        </a-form-item>
        <!-- 规则说明 -->
        <a-form-item label="规则说明" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
          <a-input
            placeholder="请输入规则说明(最多500个字符)"
            allowClear
            :autoSize="{minRows: 3}"
            type="textarea"
            :maxLength="500"
            id="addSetModal-remarks"
            v-decorator="['formData.remarks', {
              initialValue: formData.remarks,getValueFromEvent: $filterEmpty,
              rules: [] }]" />
        </a-form-item>
        <!-- 箱体限投 -->
        <a-row type="flex" align="middle" v-for="(item, index) in codeList" :key="index">
          <a-col span="11">
            <!-- 请输入投放重量 -->
            <a-form-item :label="item.dispName" :required="true" :label-col=" { span: 11 }" :wrapper-col=" { span: 13 }">
              <a-input-number
                :id="'addSetModal-rubbishWeight'+index"
                :min="0"
                :max="999999"
                :precision="0"
                :disabled="item.state==0"
                style="width: 150px;"
                placeholder="请输入投放重量"
                v-decorator="[
                  `formData.rubbishWeight[${index}]`,
                  {
                    validateTrigger: ['change', 'blur'],
                    initialValue:formData[`rubbishWeight[${index}]`],
                    rules: [
                      {
                        required: item.state==1?true:false, message: '请输入投放重量(最大999999)!'
                      },
                    ],
                  },
                ]" />
              <span>（g）</span>
            </a-form-item>
          </a-col>
          <a-col span="1"></a-col>
          <a-col span="8">
            <!-- 请输入可兑乐豆数 -->
            <a-form-item :label="''" :required="false" :wrapper-col="{ span: 20 }">
              <a-input-number
                :id="'addSetModal-goleNum'+index"
                :min="0"
                :max="999999"
                :precision="0"
                :disabled="item.state==0"
                style="width: 140px;"
                placeholder="请输入可兑乐豆数"
                v-decorator="[
                  `formData.goleNum[${index}]`,
                  {
                    validateTrigger: ['change', 'blur'],
                    initialValue:formData[`goleNum[${index}]`],
                    rules: [
                      {
                        required: item.state==1?true:false, message: '请输入可兑乐豆数(最大999999)!'
                      },
                    ],
                  },
                ]" />
              <span>（个）</span>
            </a-form-item>
          </a-col>
          <a-col span="3">
            <a-form-item :label="''" :required="false" :wrapper-col="{ span: 24 }">
              <a-checkbox id="addSetModal-state" :checked="item.state==0" @change="handleStatusChange(item,index)">
                不兑换
              </a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item :wrapper-col="{ span: 24, offset: 10 }">
          <a-button type="primary" @click="handleSubmit()" id="addSetModal-handleSubmit" :style="{ marginRight: '15px' }">
            保存
          </a-button>
          <a-button :style="{ marginLeft: '15px' }" @click="cancel()" id="addSetModal-handleCancel">
            取消
          </a-button>
        </a-form-item>
      </a-form>

    </a-modal>
  </div>
</template>

<script>
import {
  STable,
  VSelect
} from '@/components'
import {
  viewExchangeSetting,
  saveExchangeSetting
} from '@/api/exchangeSetting.js'
import {
  getLookUpData
} from '@/api/data'
export default {
  name: 'RoleModal',
  components: {
    STable,
    VSelect
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String, Number],
      default: function () {
        return ''
      }
    },
    // 兑换编码
    goldExRuleNo: {
      type: [String, Number],
      default: function () {
		  return ''
      }
    }
  },
  data () {
    return {
      titleText: '新增',
      isshow: this.visible,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, {
        name: 'AddBoxModal'
      }),
      formData: {
        name: '',
        remarks: '',
        goldExRuleItemList: [],
        goleNum: [],
        rubbishWeight: []
      },
      codeList: []
    }
  },
  methods: {
    // 查询分类数据字典
    getTypeCode () {
      getLookUpData({
        pageNo: 1,
        pageSize: 1000,
        lookupCode: 'RUBBISH_TYPE'
      }).then(res => {
        const list = res.data.list
        list.map(item => {
          item.state = item.dispName == '有害垃圾' ? 0 : 1
        })
        this.codeList = list
      })
    },
    // 查详情
    getDetailData (id) {
      viewExchangeSetting({
        id: id
      }).then(res => {
        if (res.status == 200) {
          this.formData = Object.assign({}, this.formData, res.data)
          // 回显数据
          this.formData.goldExRuleItemList.map((item, index) => {
            this.formData['goleNum[' + index + ']'] = item.goleNum
            this.formData['rubbishWeight[' + index + ']'] = item.rubbishWeight
            this.codeList[index].state = item.state
          })
        }
      })
    },
    // 是否兑换切换
    handleStatusChange (item, index) {
      item.state = item.state ? 0 : 1
      this.formData['goleNum[' + index + ']'] = 0
      this.formData['rubbishWeight[' + index + ']'] = 0
      this.form.resetFields([`formData.rubbishWeight[${index}]`, `formData.goleNum[${index}]`])
    },
    // 保存提交
    handleSubmit () {
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          const params = Object.assign({}, this.formData, values.formData)
          // 编辑
          if (this.id) {
            console.log(0, ' params')
            params.id = this.id
            params.goldExRuleNo = this.goldExRuleNo
            // console.log(params, ' params')
            // 编辑格式化数据
            this.codeList.map((item, index) => {
              params.goldExRuleItemList[index] = Object.assign({}, params.goldExRuleItemList[index], {
                state: item.state,
                rubbishType: item.code,
                goleNum: params.goleNum[index],
                rubbishWeight: params.rubbishWeight[index]
              })
              delete params[`goleNum[${index}]`]
              delete params[`rubbishWeight[${index}]`]
              delete params.goldExRuleItemList[index].id
            })
          } else {
            // 新增格式化数据
            this.codeList.map((item, index) => {
              params.goldExRuleItemList[index] = {
                state: item.state,
                rubbishType: item.code,
                goleNum: params.goleNum[index],
                rubbishWeight: params.rubbishWeight[index]
              }
            })
          }
          console.log(params, ' params')
          saveExchangeSetting(params).then(res => {
            console.log(res, 'res--save')
            if (res.status + '' === '200') {
              this.$message.success(res.message ? res.message : '保存成功')
              this.$emit('refresh')
              setTimeout(function () {
                _this.cancel()
              }, 300)
            } else {
              // this.$message.error(res.message)
            }
          })
        }
      })
    },
    cancel (e) {
      this.clear()
      this.$emit('close')
    },
    clear () {
      this.form.resetFields()
      this.formData = {
        name: '',
        remarks: '',
        goldExRuleItemList: [],
        goleNum: [],
        rubbishWeight: []
      }
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, {
      name: 'AddBoxModal'
    })
  },
  created () {
    this.getTypeCode()
  },
  watch: {
    visible (newValue, oldValue) {
      this.isshow = newValue
    },
    isshow (newValue, oldValue) {
      if (newValue) {
        if (this.id) {
          this.form.resetFields()
          this.titleText = '编辑'
		  this.getDetailData(this.id)
        } else {
          this.titleText = '新增'
          this.codeList.map(item => {
            item.state = item.dispName == '有害垃圾' ? 0 : 1
          })
        }
      } else {
        this.cancel()
      }
    }
  }
}
</script>

<style scoped>
	.modalBox {}

	.ant-modal-footer {
		display: none;
	}

	.dynamic-delete-button {
		margin-right: 20px;
	}

	.linenums {
		padding: 0 20px;
	}
</style>
