<template>
  <a-modal
    centered
    class="promotionList-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    :title="itemSn?'编辑':'新增'"
    v-model="isShow"
    @cancel="isShow=false"
    :width="800">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="promotionList-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol" >
        <a-form-model-item label="促销名称" prop="supplierSn">
          <a-input id="promotionList-promotionName" v-model.trim="form.promotionName" allowClear placeholder="请输入促销名称（最多30个字符）" :maxLength="30"></a-input>
        </a-form-model-item>
        <a-form-model-item label="促销时间" prop="supplierSn">
          <a-range-picker
            style="width:100%"
            id="promotionList-basicInfo-activeDate"
            :disabledDate="disabledDate"
            v-model="form.activeDate"
            :format="dateFormat"
            :placeholder="['开始时间', '结束时间']"></a-range-picker>
        </a-form-model-item>
        <a-form-model-item label="费用所属部门" prop="returnReason">
          <v-select
            v-model="form.returnReason"
            ref="returnReason"
            id="promotionList-basicInfo-returnReason"
            code="SPARE_PARTS_RETURN_REASON"
            placeholder="请选择费用所属部门"
            allowClear></v-select>
        </a-form-model-item>
        <a-form-model-item label="参与客户" prop="supplierSn">
          <a-row :gutter="15">
            <a-col :md="5" :sm="24">
              <a-button type="primary" :loading="spinning" @click="handleDealerModal">选择</a-button>
            </a-col>
            <a-col :md="6" :sm="24" v-show="chooseDealerList && chooseDealerList.length>0">
              已{{ chooseDealerList.length }}选项
            </a-col>
            <a-col :md="24" :sm="24" v-show="chooseDealerList && chooseDealerList.length>0">
              <div class="buyerBox">
                <a-tag closable v-for="con in chooseDealerList" :key="con.buyerSn" @close="delBuyerName(con)">
                  {{ con.buyerName }}
                </a-tag>
              </div>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="促销描述" prop="explainInfo">
          <a-textarea
            id="promotionList"
            :maxLength="500"
            :rows="5"
            v-model="form.explainInfo"
            placeholder="请输入促销描述"
            allowClear />
        </a-form-model-item>
        <a-form-model-item label="附件" help="（支持图片、word、excel、PDF等格式，最多10个附件）">
          <Upload
            style="height: 100%;"
            id="allocateBill-attachList"
            v-model="form.attachmentList"
            ref="attachList"
            :fileSize="10"
            :maxNums="10"
            fileType="*"
            uploadType="attach"
            :action="attachAction"
            @change="changeAttach"
            upText="上传附件"></Upload>
        </a-form-model-item>
      </a-form-model>
      <div class="btn-cont">
        <a-button id="promotionList-basicInfo-modal-back" @click="isShow = false">取消</a-button>
        <a-button style="margin-left: 15px;" type="primary" id="promotionList-modal-save" @click="handleSave">确定</a-button>
      </div>
    </a-spin>
    <!-- 选择参与客户 -->
    <a-modal
      title="选择经销商"
      :visible="openDealerModal"
      :footer="null"
      centered
      class="lookUpCustomers-modal"
      @cancel="openDealerModal = false"
      width="60%"
    >
      <div class="dealerModalCon">
        <chooseDealer ref="dealerChoose" @plAdd="handleAddDealer"></chooseDealer>
      </div>
    </a-modal>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { VSelect, Upload } from '@/components'
import supplier from '@/views/common/supplier.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import moment from 'moment'
import chooseDealer from '../promotionManagement/chooseDealer'
import { sparePartsReturnSave, sparePartsReturnInfo } from '@/api/sparePartsReturn'
export default {
  name: 'PromotionListBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect, Upload, supplier, warehouse, chooseDealer },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 }
      },
      form: {
        promotionName: '',
        activeDate: undefined,
        supplierSn: undefined, // 供应商
        returnReason: '', // 退货原因
        explainInfo: '', // 补充说明
        warehouseSn: undefined,
        attachmentList: ''
      },
      openDealerModal: false,
      chooseDealerList: [],
      attachList: [], // 附件
      dateFormat: 'YYYY-MM-DD',
      rules: {
        supplierSn: [
          { required: true, message: '请选择供应商名称', trigger: 'change' }
        ],
        returnReason: [
          { required: true, message: '请选择退货原因', trigger: 'change' }
        ],
        warehouseSn: [{ required: true, message: '请选择退货仓库', trigger: 'change' }]
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo'
    }
  },
  methods: {
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    // 选择参与客户
    handleDealerModal () {
      this.openDealerModal = true
      const _this = this
      if (_this.chooseDealerList.length == 0) {
        _this.form.promoBuyerList = []
      }
      const arr = _this.chooseDealerList.map(item => {
        return item.buyerSn
      })
      // 选择经销商回显
      _this.$nextTick(() => {
        _this.$refs.dealerChoose.pageInit(arr)
      })
    },
    // 添加经销商
    handleAddDealer (list) {
      this.chooseDealerList = list.map(con => {
        return {
          buyerSn: con.dealerSn,
          buyerName: con.dealerName
        }
      })
      this.openDealerModal = false
      // 移除表单必填项
      this.$refs.ruleForm.clearValidate('promoBuyerList')
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.attachmentList = _this.attachList
          _this.spinning = true
          sparePartsReturnSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                _this.isShow = false
                _this.$emit('ok', res.data)
                _this.spinning = false
              }, 1000)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 获取编辑详情
    getDetail () {
      sparePartsReturnInfo({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const resultObj = res.data
          this.attachList = resultObj.attachmentList
          const obj = {
            supplierSn: resultObj.supplierSn,
            returnReason: resultObj.returnReason, // 退货原因
            explainInfo: resultObj.explainInfo, // 补充说明
            warehouseSn: resultObj.warehouseSn,
            sparePartsReturnSn: this.itemSn
          }
          this.$nextTick(() => {
            this.$refs.attachList.setFileList(this.attachList)
          })
          this.form = { ...this.form, ...obj }
        } else {
          this.detailsData = null
        }
      })
    },
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf('day') < moment().subtract(1, 'day') // 今天以后，包含今天
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.attachList = []
        this.supplierName = null
        this.$nextTick(() => {
          this.$refs.attachList.setFileList('')
          this.$refs.ruleForm.resetFields()
        })
      } else {
        if (this.itemSn) {
          this.getDetail()
        } else {
          // 默认仓库
          this.form.warehouseSn = this.isShowWarehouse ? undefined : this.defWarehouse && this.defWarehouse.warehouseSn
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .promotionList-basicInfo-modal{
    .ant-modal-body {
      padding: 40px 40px 24px;
    }
    .buyerBox{
      border:1px solid #d9d9d9;margin-top:10px;border-radius:4px;padding:4px 10px;background:#f2f2f2;max-height:130px;overflow-y:scroll;
    }
    .btn-cont {
      text-align: center;
      margin: 35px 0 10px;
    }
  }

</style>
