<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
        style="max-height:650px;overflow-y: scroll;"
        id="promotionList-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol" >
        <a-form-model-item label="促销名称" prop="title">
          <a-input id="promotionList-promotionName" v-model.trim="form.title" allowClear placeholder="请输入促销名称（最多30个字符）" :maxLength="30"></a-input>
        </a-form-model-item>
        <a-form-model-item label="促销简称" prop="description">
          <a-input id="promotionList-description" v-model.trim="form.description" allowClear placeholder="请输入促销简称（最多20个字符）" :maxLength="20"></a-input>
        </a-form-model-item>
        <a-form-model-item label="促销时间" prop="activeDate">
          <a-range-picker
            style="width:100%"
            id="promotionList-basicInfo-activeDate"
            :disabledDate="disabledDate"
            v-model="form.activeDate"
            :format="dateFormat"
            :placeholder="['开始时间', '结束时间']"
            @change="onChangeDate"></a-range-picker>
        </a-form-model-item>
        <a-form-model-item label="费用所属部门" prop="expenseDepartmentSn">
          <department style="width: 100%;" @change="departementChange" id="promotionList-basicInfo-activeDate" v-model="form.expenseDepartmentSn"></department>
        </a-form-model-item>
        <a-form-model-item label="参与客户" prop="dealerScope">
          <a-row :gutter="15">
            <a-col :md="12" :sm="24">
              <a-select v-model="form.dealerScope" placeholder="请选择参与客户">
                <a-select-option value="ALL_DEALER">全部客户</a-select-option>
                <a-select-option value="SOME_DEALER">部分客户</a-select-option>
              </a-select>
            </a-col>
            <a-col :md="3" :sm="24" v-show="form.dealerScope &&form.dealerScope!='ALL_DEALER' ">
              <a-button type="primary" :loading="spinning" @click="handleDealerModal">选择</a-button>
            </a-col>
            <a-col :md="4" :sm="24" v-show="form.dealerScope &&form.dealerScope!='ALL_DEALER' ">
              <a-button type="primary" :loading="spinning" @click="openGuideModal=true" ghost>导入客户</a-button>
            </a-col>
            <a-col :md="5" :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.dealerSn" @close="delBuyerName(con)">
                  {{ con.dealerName }}
                </a-tag>
              </div>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="促销描述" prop="content">
          <a-textarea
            id="promotionList-content"
            :maxLength="500"
            :rows="5"
            v-model="form.content"
            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" pageType="dealerPromotion" @plAdd="handleAddDealer"></chooseDealer>
      </div>
    </a-modal>
    <!-- 导入参与客户 -->
    <importDealerModa :openModal="openGuideModal" @close="openGuideModal=false" @ok="hanldeOk" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { Upload } from '@/components'
import department from '@/views/expenseManagement/expenseReimbursement/department.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import moment from 'moment'
import chooseDealer from '../promotionManagement/chooseDealer'
import importDealerModa from './importDealerModa.vue'
import { dealerPromotionSave, dealerPromotionInfo, dealerPromotionEdit } from '@/api/promotion'
export default {
  name: 'PromotionListBasicInfoModal',
  mixins: [commonMixin],
  components: { Upload, department, warehouse, chooseDealer, importDealerModa },
  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: {
        title: '',
        activeDate: undefined,
        expenseDepartmentSn: undefined, // 费用所属部门
        description: '', // 活动简称
        content: '', // 活动描述
        attachmentList: '', // 附件
        dealerSnList: [], // 参与客户
        dealerScope: 'SOME_DEALER' // 全部客户   部分客户
      },
      openDealerModal: false,
      chooseDealerList: [],
      attachList: [], // 附件
      dateFormat: 'YYYY-MM-DD',
      rules: {
        title: [{ required: true, message: '请输入促销名称', trigger: 'blur' }],
        activeDate: [{ required: true, message: '请选择促销时间', trigger: 'change' } ],
        expenseDepartmentSn: [{ required: true, message: '请选择费用所属部门', trigger: 'change' }],
        dealerScope: [{ required: true, message: '请选择参与客户', trigger: 'change' }],
        description: [{ required: true, message: '请输入促销简称', trigger: 'blur' }],
        content: [{ required: true, message: '请输入促销描述', trigger: 'blur' }]
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo',
      openGuideModal: false
    }
  },
  methods: {
    // 选择活动时间
    onChangeDate (date, dateString) {
      this.form.activeDate = date
      if (dateString[0] != '' && dateString[1] != '') {
        this.form.promotionDateStart = dateString[0] + ' 00:00:00'
        this.form.promotionDateEnd = dateString[1] + ' 23:59:59'
      }
    },
    // 费用所属部门
    departementChange () {
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('expenseDepartmentSn')
      })
    },
    //  附件上传
    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.dealerSnList = []
      }
      const arr = _this.chooseDealerList.map(item => {
        return item.dealerSn
      })
      // 选择参与客户回显
      _this.$nextTick(() => {
        _this.$refs.dealerChoose.pageInit(arr)
      })
    },
    // 删除所选参与客户
    delBuyerName (row) {
      const pot = this.chooseDealerList.findIndex(con => { return con.dealerSn == row.dealerSn })
      this.chooseDealerList.splice(pot, 1)
    },
    // 添加经销商
    handleAddDealer (list) {
      this.chooseDealerList = list
      this.openDealerModal = false
      // 移除表单必填项
      this.$refs.ruleForm.clearValidate('dealerSnList')
    },
    //  新增/编辑
    handleSave () {
      const _this = this
      const newArr = this.chooseDealerList.map(item => {
        return item.dealerSn
      })
      _this.form.dealerSnList = newArr
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.attachmentList = _this.attachList
          delete form.activeDate
          _this.spinning = true
          const ajaxName = _this.itemSn ? dealerPromotionEdit : dealerPromotionSave
          ajaxName(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
        }
      })
    },
    // 重置
    resetSearchForm () {
      this.form = {
        title: '',
        activeDate: undefined,
        expenseDepartmentSn: undefined, // 费用所属部门
        description: '', // 活动简称
        content: '', // 活动描述
        attachmentList: '', // 附件
        dealerSnList: [], // 参与客户
        dealerScope: 'SOME_DEALER'
      }
      this.attachList = []
      this.chooseDealerList = []
      this.$nextTick(() => {
        this.$refs.attachList.setFileList('')
        this.$refs.ruleForm.resetFields()
      })
    },
    // 获取编辑详情
    getDetail () {
      dealerPromotionInfo({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          const data = res.data
          this.chooseDealerList = data.dealerList
          data.dealerSnList = data.dealerSnList
          data.activeDate = [data.promotionDateStart, data.promotionDateEnd]
          if (data.attachmentList) {
            this.attachList = data.attachmentList
            this.$nextTick(() => {
              this.$refs.attachList.setFileList(this.attachList)
            })
          }
          this.form = data
        }
      })
    },
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf('day') < moment().subtract(1, 'day') // 今天以后，包含今天
    },
    // 导入参与客户
    hanldeOk (arr) {
      this.chooseDealerList = this.chooseDealerList.concat(arr)
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      } else {
        if (this.itemSn) {
          this.getDetail()
        }
      }
    }
  }
}
</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>
