<template>
  <a-modal
    centered
    class="allocateBill-basicInfo-modal"
    :footer="null"
    :maskClosable="false"
    :title="isEdit?'编辑':'新增'"
    v-model="isShow"
    @cancel="isShow = false"
    :width="900">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="allocateBill-basicInfo-form"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol"
      >
        <a-row :gutter="15">
          <a-col :md="12" :sm="24" v-if="!isEdit">
            <a-form-model-item label="调往对象" prop="targetType">
              <a-radio-group v-model="form.targetType" @change="targetTypeChange">
                <a-radio v-for="(item,index) in targetTypeList" :key="index" :value="item.code">{{ item.dispName }}</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24" v-if="!isEdit">
            <a-form-model-item label="调往对象名称" :prop="isDealer||isDepartment ? 'targetSn' : 'targetName'">
              <a-select
                v-if="isDealer"
                show-search
                id="allocateBill-basicInfo-dealerName"
                v-model="form.targetSn"
                placeholder="请选择经销商"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="fetchUser"
                @change="handleChange"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option v-for="item in dealerData" :key="item.dealerSn" :value="item.dealerSn">{{ item.dealerName }}</a-select-option>
              </a-select>
              <department v-else-if="isDepartment" style="width: 100%;" placeholder="请选择部门" @change="departementChange" v-model="form.targetSn"></department>
              <a-input v-else v-model="form.targetName" placeholder="请输入调往对象名称(最多30个字符)" :maxLength="30"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24" v-if="!isEdit">
            <a-form-model-item label="调出仓库" prop="warehouseSn">
              <warehouse
                isPermission
                v-model="form.warehouseSn"
                ref="warehouse"
                id="allocateBill-basicInfo-warehouseSn"
                placeholder="请选择调出仓库"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item label="费用/调拨类型" prop="costTypeSn">
              <AllocateType id="allocateBill-basicInfo-allocateTypeSn" v-model="allocateTypeVal" placeholder="请选择费用/调拨类型" @change="allocateTypeChange"></AllocateType>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item
              label="费用归属品牌"
              prop="productBrandSn"
              :required="form.costTypeName=='促销费用'"
            >
              <ProductBrand id="allocateBill-basicInfo-productBrandSn" @change="changeBrand" showAllBrand v-model="form.productBrandSn" placeholder="请选择费用归属品牌(单选)"></ProductBrand>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item
              label="费用归属品类"
              prop="productTypeSn2"
              :required="form.costTypeName=='促销费用'"
            >
              <productTypeAll
                :isAll="true"
                placeholder="请选择费用归属品类(单选,至少选到二级或三级)"
                showAllType
                @change="changeProductType"
                v-model="productType"
                id="allocateBill-basicInfo-productType"></productTypeAll>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item label="起止时间" prop="time">
              <a-range-picker
                style="width:100%"
                v-model="form.time"
                :format="dateFormat"
                @change="dateChange"
                :placeholder="['开始时间', '结束时间']" />
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item style="margin-bottom:10px;" label="备注" prop="remark" :wrapperCol="{ span: 20 }" :labelCol="{ span: 4 }">
              <a-textarea id="allocateBill-basicInfo-remark" :maxLength="100" v-model="form.remark" placeholder="请输入备注(最多100个字符)" allowClear />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <a-form-model-item label="附件" help="（支持图片、word、excel、PDF等格式，最多10个附件）" :label-col="{span:4}" :wrapper-col="{span:18}">
              <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-col>
        </a-row>
      </a-form-model>
      <div class="btn-cont">
        <a-button type="primary" :loading="spinning" id="allocateBill-basicInfo-modal-save" @click="handleSave">保存</a-button>
        <a-button id="allocateBill-basicInfo-modal-back" @click="isShow = false" style="margin-left: 15px;">取消</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import debounce from 'lodash/debounce'
import { VSelect, Upload } from '@/components'
import { allocateBillSave } from '@/api/allocateBill'
import { dealerSubareaScopeList } from '@/api/dealer'
import { getLookUpData } from '@/api/data'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
import AllocateType from '@/views/common/allocateType.js'
import warehouse from '@/views/common/chooseWarehouse.js'
import department from '@/views/expenseManagement/expenseReimbursement/department.js'
export default {
  name: 'TransferOutBasicInfoModal',
  mixins: [commonMixin],
  components: { VSelect, Upload, ProductBrand, productTypeAll, AllocateType, department, warehouse },
  props: {
    openModal: {
      //  弹框显示状态
      type: Boolean,
      default: false
    },
    detailData: Object
  },
  data () {
    this.lastFetchId = 0
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      isShow: this.openModal, //  是否打开弹框
      spinning: false,
      formItemLayout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 }
      },
      productType: [],
      attachList: [],
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo',
      form: {
        targetType: 'DEALER',
        targetSn: undefined,
        targetName: '',
        costTypeSn: '',
        allocateTypeSn: '',
        allocateSortSn: '',
        warehouseSn: undefined, // 仓库
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        time: [],
        promoStartDate: '',
        promoEndDate: '',
        remark: '',
        attachmentList: ''
      },
      rules: {
        targetType: [{ required: true, message: '请选择调往对象', trigger: 'change' }],
        targetSn: [{ required: true, message: '请选择调往对象名称', trigger: 'change' }],
        costTypeSn: [{ required: true, message: '请选择费用/调拨类型', trigger: 'change' }],
        warehouseSn: [{ required: true, message: '请选择调出仓库', trigger: 'change' }],
        targetName: [{ required: true, message: '请输入调往对象名称', trigger: 'blur' }]
      },
      fetching: false,
      dealerData: [], //  经销商  下拉数据
      targetTypeList: [], //  调往对象类型
      allocateTypeVal: [],
      dateFormat: 'YYYY-MM-DD',
      isEdit: false
    }
  },
  computed: {
    // 当前所选调往对象是否为经销商
    isDealer () {
      return this.form.targetType == 'DEALER'
    },
    isDepartment () {
      return this.form.targetType == 'DEPARTMENT'
    }
  },
  methods: {
    // 日期  change
    dateChange (date, dateStrings) {
      console.log(date, dateStrings)
      this.form.time = dateStrings
      this.form.promoStartDate = date.length ? dateStrings[0] : ''
      this.form.promoEndDate = date.length ? dateStrings[1] : ''
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    departementChange (v, row) {
      console.log(v, row)
      this.form.targetName = row.name
    },
    // 调拨类别 change
    allocateTypeChange (val, opt) {
      console.log(val, opt, '------------')
      this.allocateTypeVal = val || ''
      this.form.costTypeSn = val && val[0] ? val[0] : ''
      this.form.allocateSortSn = val && val[1] ? val[1] : ''
      this.form.allocateTypeSn = val && val[2] ? val[2] : ''
      // 名称
      this.form.costTypeName = opt && opt[0] ? opt[0].name : ''
      this.form.allocateSortName = opt && opt[1] ? opt[1].name : ''
      this.form.allocateTypeName = opt && opt[2] ? opt[2].name : ''
      // 校验规则
      this.$refs.ruleForm.clearValidate()
      this.valiadBranType()
    },
    valiadBranType () {
      if (this.form.costTypeName == '促销费用') {
        this.rules.productBrandSn = [{ required: true, message: '请选择归属品牌', trigger: 'change' }]
        this.rules.productTypeSn2 = [{ required: true, message: '请选择归属分类(至少选择到2级或3级分类)', trigger: 'change' }]
      } else {
        this.rules.productBrandSn = []
        this.rules.productTypeSn2 = []
      }
    },
    //  产品分类  change
    changeProductType (val, id, opt) {
      console.log(val, opt, '------------')
      this.form.productTypeSn1 = val && val[0] ? val[0] : ''
      this.form.productTypeSn2 = val && val[1] ? val[1] : ''
      this.form.productTypeSn3 = val && val[2] ? val[2] : ''
      // 名称
      this.form.productTypeName1 = opt && opt[0] ? opt[0].productTypeName : ''
      this.form.productTypeName2 = opt && opt[1] ? opt[1].productTypeName : ''
      this.form.productTypeName3 = opt && opt[2] ? opt[2].productTypeName : ''
    },
    // 品牌
    changeBrand (val, id, opt) {
      this.form.productBrandName = opt ? opt.brandName : ''
    },
    fetchUser (dealerName) {
      if (dealerName == '') return
      this.lastFetchId += 1
      const fetchId = this.lastFetchId
      this.dealerData = []
      this.fetching = true
      dealerSubareaScopeList({ nameLike: dealerName.replace(/\s+/g, ''), pageNo: 1, pageSize: 20 }).then(res => {
        if (fetchId !== this.lastFetchId) {
          return
        }
        this.dealerData = res.data && res.data.list ? res.data.list : []
        this.fetching = false
      })
    },
    // 调往对象名称经销商  change
    handleChange (value) {
      const ind = this.dealerData.findIndex(item => item.dealerSn == value)
      this.form.targetName = this.dealerData[ind].dealerName
      const wsn = this.dealerData[ind].defaultWarehouseSn
      if (this.$refs.warehouse.hasWarehouse(wsn)) {
        this.form.warehouseSn = wsn
      } else {
        this.form.warehouseSn = undefined
      }
    },
    //  保存
    handleSave () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          if (!form.productBrandName) {
            form.productBrandSn = ''
          }
          form.attachmentList = this.attachList
          // 判断费用归属品类  最少要选择到2级或3级分类
          if (_this.form.productTypeSn1 && !_this.form.productTypeSn2) {
            _this.$message.warning('请选择归属分类(至少选择到2级或3级分类)')
            return false
          }
          _this.spinning = true
          allocateBillSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.isShow = false
              _this.$emit('ok', res.data)
            }
            _this.spinning = false
          })
        } else {
          _this.spinning = false
          return false
        }
      })
    },
    // 调往对象  change
    targetTypeChange (e) {
      this.form.targetSn = undefined
      this.form.targetName = ''
      this.form.warehouseSn = undefined
      this.form.targetType = e.target.value
    },
    // 调往对象类型
    getTargetTypeList () {
      const _this = this
      getLookUpData({
        pageNo: 1,
        pageSize: 1000,
        lookupCode: 'TARGET_TYPE'
      }).then(res => {
        if (res.status == 200) {
          _this.targetTypeList = res.data.list
        } else {
          _this.targetTypeList = []
        }
      })
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.$refs.ruleForm.resetFields()
        this.allocateTypeVal = []
        this.productType = []
        this.attachList = []
        this.rules.productBrandSn = []
        this.rules.productTypeSn2 = []
        this.form.attachmentList = ''
        this.$refs.attachList.setFileList('')
        this.form = {
          targetType: 'DEALER',
          targetSn: undefined,
          targetName: '',
          costTypeSn: '',
          allocateTypeSn: '',
          allocateSortSn: '',
          warehouseSn: undefined,
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '', //  产品三级分类
          time: [],
          promoStartDate: '',
          promoEndDate: '',
          remark: ''
        }
      } else {
        this.getTargetTypeList()
        // 编辑
        if (this.detailData) {
          this.isEdit = true
          this.form = Object.assign(this.form, this.detailData)
          // 获取附件列表
          this.form.attachmentList = ''
          this.attachList = this.detailData.attachmentList
          this.$nextTick(() => {
            this.$refs.attachList.setFileList(this.attachList)
          })
          this.allocateTypeVal = [this.detailData.costTypeSn, this.detailData.allocateSortSn, this.detailData.allocateTypeSn]
          if (this.detailData.productTypeSn1) {
            this.productType = [this.detailData.productTypeSn1, this.detailData.productTypeSn2, this.detailData.productTypeSn3]
          }
          if (this.form.promoStartDate && this.form.promoEndDate) {
            this.form.time = [this.form.promoStartDate, this.form.promoEndDate]
          }
          if (!this.form.productBrandSn) {
            this.form.productBrandSn = undefined
          }
          this.valiadBranType()
        }
      }
    }
  }
}
</script>

<style lang="less">
.allocateBill-basicInfo-modal {
	.ant-modal-body {
		padding: 40px 40px 24px;
	}
	.btn-cont {
		text-align: center;
		margin: 35px 0 10px;
	}
}
</style>
