<template>
  <a-modal
    centered
    class="promotionList-basicInfo-modal"
    id="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-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 id="promotionList-dealerScope" v-model="form.dealerScope" placeholder="请选择参与客户" @change="changeDealerScope" allowClear>
                <a-select-option id="promotionList-dealerScope-all" value="ALL_DEALER">全部客户</a-select-option>
                <a-select-option id="promotionList-dealerScope-some" 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 id="promotionList-basicInfo-dealerScope" 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 id="promotionList-basicInfo-import" 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" id="promotionList-dealerSn" :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="dealerMaxJoinFlag">
          <a-select default-value="0" id="promotionList-dealerMaxJoinFlag" v-model="form.dealerMaxJoinFlag" style="width: 180px" placeholder="请选择">
            <a-select-option value="0" id="promotionList-dealerMaxJoinFlag0">
              不限
            </a-select-option>
            <a-select-option value="1" id="promotionList-dealerMaxJoinFlag1">
              限制
            </a-select-option>
          </a-select>
          <a-input-number
            v-show="form.dealerMaxJoinFlag && form.dealerMaxJoinFlag=='1'"
            style="margin-left:10px;width:300px;"
            v-model="form.dealerMaxJoinQty"
            id="promotionList-dealerMaxJoinQty"
            :min="1"
            :step="1"
            :max="99999999"
            :precision="0"
            placeholder="请输入最大参与次数"/>
        </a-form-model-item>
        <a-form-model-item label="订单起订金额" prop="minOrderFlag">
          <a-select default-value="0" id="promotionList-minOrderFlag" v-model="form.minOrderFlag" style="width: 180px" placeholder="请选择">
            <a-select-option value="0" id="promotionList-minOrderFlag0">
              不限
            </a-select-option>
            <a-select-option value="1" id="promotionList-minOrderFlag1">
              限制
            </a-select-option>
          </a-select>
          <a-input-number
            v-show="form.minOrderFlag && form.minOrderFlag=='1'"
            style="margin-left:10px;width:300px;"
            v-model="form.minOrderAmount"
            id="promotionList-minOrderAmount"
            :min="0"
            :step="1"
            :max="99999999"
            :precision="2"
            placeholder="请输入金额"/>
        </a-form-model-item>
        <!-- <a-form-model-item label="活动经费上限" prop="upperLimitFlag">
          <a-select default-value="0" id="promotionList-upperLimitFlag" v-model="form.upperLimitFlag" style="width: 180px" placeholder="请选择">
            <a-select-option value="0" id="promotionList-upperLimitFlag0">
              不限
            </a-select-option>
            <a-select-option value="1" id="promotionList-upperLimitFlag1">
              限制
            </a-select-option>
          </a-select>
          <a-input-number
            v-show="form.upperLimitFlag&&form.upperLimitFlag=='1'"
            style="margin-left:10px;width:300px;"
            v-model="form.upperLimitAmount"
            id="promotionList-upperLimitAmount"
            :min="0"
            :step="1"
            :max="99999999"
            :precision="2"
            placeholder="请输入金额"/>
        </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="promotionList-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-modal-cancel" @click="isShow = false">取消</a-button>
        <a-button style="margin-left: 15px;" type="primary" id="promotionList-modal-save" :loading="loadingSave" @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>
    <!-- 导入参与客户 -->
    <importDealerModa :openModal="openGuideModal" @close="openGuideModal=false" @ok="hanldeOk" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
// 组件
import { Upload } from '@/components'
import department from '@/views/expenseManagement/expenseReimbursement/department.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import chooseDealer from './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 {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      // 表单label布局
      formItemLayout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 }
      },
      // 提交参数
      form: {
        title: '', // 促销名称
        activeDate: undefined, // 促销时间
        expenseDepartmentSn: undefined, // 费用所属部门
        description: '', // 活动简称
        content: '', // 活动描述
        attachmentList: '', // 附件
        promotionDealerList: [], // 参与客户
        dealerScope: 'SOME_DEALER', // 全部客户   部分客户
        dealerMaxJoinFlag: '0',
        dealerMaxJoinQty: undefined,
        minOrderFlag: '0', // 订单起订量
        minOrderAmount: undefined, // 订单起订金额
        upperLimitFlag: '0', // 活动经费上限
        upperLimitAmount: undefined// 活动经费上限金额
      },
      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' }],
        dealerMaxJoinFlag: [{ required: true, message: '请选择最大参与次数', trigger: 'change' }],
        minOrderFlag: [{ required: true, message: '请选择订单起订金额', trigger: 'change' }],
        // upperLimitFlag: [{ required: true, message: '请选择活动经费上限', trigger: 'change' }],
        content: [{ required: true, message: '请输入促销描述', trigger: 'blur' }]
      },
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo', // 上传附件地址
      openGuideModal: false, // 导入参与客户弹窗
      loadingSave: 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 = file ? 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.promotionDealerList = []
      }
      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('promotionDealerList')
    },
    //  新增/编辑
    handleSave () {
      const _this = this
      if (_this.form.dealerScope === 'SOME_DEALER') {
        if (_this.chooseDealerList && _this.chooseDealerList.length > 0) {
          const newArr = _this.chooseDealerList.map(item => {
            return { dealerSn: item.dealerSn, dealerScope: _this.form.dealerScope }
          })
          _this.form.promotionDealerList = newArr
        } else {
          _this.$message.error('请选择参与客户')
          return
        }
      } else {
        _this.form.promotionDealerList = [{ dealerScope: _this.form.dealerScope }]
        _this.form.dealerList = []
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          // 判断起订金额、活动经费上限
          if (form.minOrderFlag == '1' && !form.minOrderAmount) {
            _this.$message.error('请输入订单起订限制金额数！')
            return
          }
          if (form.upperLimitFlag == '1' && !form.upperLimitAmount) {
            _this.$message.warning('请输入活动经费上限金额！')
            return
          }
          if (form.dealerMaxJoinFlag == '1' && !form.dealerMaxJoinQty) {
            _this.$message.warning('最大参与次数必需大于0！')
            return
          }
          if (form.minOrderFlag == '0') {
            form.minOrderAmount = undefined
          }
          if (form.upperLimitFlag == '0') {
            form.upperLimitAmount = undefined
          }
          form.attachmentList = _this.attachList
          delete form.activeDate
          _this.spinning = true
          _this.loadingSave = 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
                _this.loadingSave = false
              }, 1000)
            } else {
              _this.spinning = false
              _this.loadingSave = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 选择全部客户时，清空之前选择的客户列表
    changeDealerScope (val) {
      if (val === 'ALL_DEALER') {
        this.chooseDealerList = []
      }
    },
    // 重置
    resetSearchForm () {
      this.form = {
        title: '',
        activeDate: undefined,
        expenseDepartmentSn: undefined, // 费用所属部门
        description: '', // 活动简称
        content: '', // 活动描述
        attachmentList: '', // 附件
        promotionDealerList: [], // 参与客户
        dealerScope: 'SOME_DEALER',
        dealerMaxJoinFlag: '0',
        dealerMaxJoinQty: undefined,
        minOrderFlag: '0', // 订单起订金额
        minOrderAmount: undefined,
        upperLimitFlag: '0', // 活动经费上限
        upperLimitAmount: undefined
      }
      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.promotionDealerList = data.promotionDealerList
          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) {
      const list = [...this.chooseDealerList, ...arr]
      const obj = {}
      this.chooseDealerList = list.reduce((cur, next) => {
        obj[next.dealerSn] ? '' : obj[next.dealerSn] = true && cur.push(next)
        return cur
      }, [])
    }
  },
  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>
