<template>
  <a-modal
    v-drag
    v-model="opened"
    :title="title"
    centered
    :maskClosable="false"
    :width="800"
    :footer="null"
    @cancel="cancel"
  >
    <a-spin :spinning="spinning" tip="Loading...">
      <a-form-model
        id="expenseReimbursementAddform"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="formItemLayout.labelCol"
        :wrapper-col="formItemLayout.wrapperCol">
        <a-row>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item label="申请人" prop="applyPersonSn">
              <employee style="width: 100%;" @change="employeeChange" id="expenseReimbursementAddform-Employee" v-model="form.applyPersonSn"></employee>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item label="申请部门" prop="applyDepartmentSn">
              <department style="width: 100%;" @change="departementChange" id="expenseReimbursementAddform-Department" v-model="form.applyDepartmentSn"></department>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item label="费用类型" prop="expenseType">
              <expenseType
                id="expenseReimbursementAddform-expenseType"
                v-model="expenseTypes"
                @change="expenseChange"
                placeholder="请选择费用类型"
              ></expenseType>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item label="费用产生月" prop="expenseDate">
              <a-month-picker
                id="expenseReimbursementAddform-expenseDate"
                placeholder="请选择月份"
                v-model="form.expenseDate"
                locale="zh-cn"
                @change="expenseDateChange"
                :disabled-date="disabledDate"
                style="width: 100%;"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item
              label="费用归属品牌"
              prop="productBrandSn"
              :required="form.expenseTypeName=='促销费用'"
            >
              <ProductBrand id="expenseReimbursementAddform-productBrandSn" @change="changeBrand" showAllBrand v-model="form.productBrandSn" placeholder="请选择费用归属品牌(单选)"></ProductBrand>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <a-form-model-item
              label="费用归属品类"
              prop="productTypeSn2"
              :required="form.expenseTypeName=='促销费用'"
            >
              <productTypeAll
                :isAll="true"
                placeholder="请选择费用归属品类(单选,至少选到二级或三级)"
                showAllType
                @change="changeProductType"
                v-model="productType"
                id="expenseReimbursementAddform-productType"></productTypeAll>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <a-form-model-item label="主题" prop="title" :label-col="{span:3}" :wrapper-col="{span:19}">
              <a-textarea
                id="expenseReimbursementAddform-title"
                :maxLength="100"
                :rows="3"
                v-model.trim="form.title"
                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="详细说明" prop="content" :label-col="{span:3}" :wrapper-col="{span:19}">
              <a-textarea
                id="expenseReimbursementAddform-content"
                placeholder="请详细描述费用报销内容（最多500个字符）"
                v-model.trim="form.content"
                :rows="3"
                :maxLength="500"
                allowClear/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <a-form-model-item label="摘要" prop="digestInfo" :label-col="{span:3}" :wrapper-col="{span:19}">
              <a-textarea
                id="expenseReimbursementAddform-digestInfo"
                placeholder="请输入费用报销摘要（最多30个字符）"
                v-model.trim="form.digestInfo"
                :maxLength="30"
                allowClear/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <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:3}" :wrapper-col="{span:19}">
              <Upload
                style="height: 100%;"
                id="expenseReimbursementAddform-attachList"
                v-model="form.expenseAccountFilesList"
                ref="attachList"
                :fileSize="10"
                :maxNums="10"
                fileType="*"
                uploadType="attach"
                :action="attachAction"
                @change="changeAttach"
                upText="上传附件"></Upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div style="text-align: center;margin-top: 20px;">
          <a-button @click="cancel" style="margin-right: 15px" id="expenseReimbursementAddform-btn-back">取消</a-button>
          <a-button type="primary" :loading="spinning" @click="handleSubmit" id="expenseReimbursementAddform-btn-submit">保存</a-button>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { VSelect, Upload, STable } from '@/components'
import moment from 'moment'
import department from './department.js'
import employee from './employee.js'
import expenseType from '@/views/common/expenseType.js'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
import { expenseAccountDetail, expenseAccountSave } from '@/api/expenseManagement.js'
export default {
  name: 'BaseDataModal',
  components: { VSelect, Upload, STable, department, employee, expenseType, ProductBrand, productTypeAll },
  props: {
    show: [Boolean],
    itemSn: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      opened: this.show,
      expenseAccountSn: this.itemSn, // 费用报销单sn
      spinning: false,
      title: '新增费用报销单', // 弹框标题
      formItemLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      fromPage: null, // 打开方式，sales：销售单转费用单，salesMearge：合并销售单转，其它手动创建
      attachList: [], // 附件列表
      attachAction: process.env.VUE_APP_API_BASE_URL + '/uploadGetFileInfo', // 附件上传地址
      expenseTypes: [], // 费用类型值
      productType: [],
      form: {
        applyPersonSn: undefined, // 申请人
        applyDepartmentSn: undefined, //  申请部门
        expenseType: undefined, //  费用类型1
        expenseType2: undefined, //  费用类型2
        expenseType3: undefined, // 费用类型3
        expenseTypeName: undefined, //  费用类型1
        expenseTypeName2: undefined, //  费用类型2
        expenseTypeName3: undefined, // 费用类型3
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        expenseDate: moment().locale('zh-cn').format('YYYY-MM'), //  费用产生月
        title: '', // 主题
        content: '', // 费用说明
        digestInfo: '' // 摘要
      }
    }
  },
  computed: {
    rules () {
      return {
        applyPersonSn: [
          { required: true, message: '请选择申请人', trigger: 'change' }
        ],
        applyDepartmentSn: [
          { required: true, message: '请选择申请部门', trigger: 'change' }
        ],
        expenseType: [
          { required: true, message: '请选择费用类型', trigger: 'change' }
        ],
        expenseDate: [
          { required: true, message: '请选择费用产生月', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入主题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入详细说明', trigger: 'blur' }
        ],
        digestInfo: [
          { required: this.form.expenseTypeName == '促销费用', message: '请输入摘要', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 关闭弹框
    cancel () {
      this.spinning = false
      this.$emit('close')
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => {
        if (this.expenseAccountSn) { //  编辑页
          this.getDetail()
          this.title = '编辑费用报销单'
        } else {
          this.title = '新增费用报销单'
        }
      })
    },
    // 重置表单
    retsetForm () {
      this.form = {
        applyPersonSn: undefined, // 申请人
        applyDepartmentSn: undefined, //  申请部门
        expenseType: undefined, //  费用类型1
        expenseType2: undefined, //  费用类型2
        expenseType3: undefined, // 费用类型3
        expenseTypeName: undefined, //  费用类型1
        expenseTypeName2: undefined, //  费用类型2
        expenseTypeName3: undefined, // 费用类型3
        productBrandSn: undefined, //  产品品牌
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        expenseDate: moment().locale('zh-cn').format('YYYY-MM'), //  费用产生月
        title: '', // 主题
        content: '', // 费用说明
        digestInfo: '' // 摘要
      }
      this.rules.productBrandSn = []
      this.rules.productTypeSn2 = []
      this.productType = []
      this.attachList = []
      this.form.expenseAccountFilesList = ''
      this.$refs.attachList.setFileList('')
      this.$refs.ruleForm.resetFields()
      this.expenseTypes = []
    },
    //  产品分类  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 : ''
    },
    // 申请人员
    employeeChange (v, r) {
      if (r.departmentSn) {
        this.form.applyDepartmentSn = r.departmentSn
      }
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField(['applyPersonSn', 'applyDepartmentSn'])
      })
    },
    // 申请部门选择
    departementChange () {
      this.$nextTick(() => {
        this.$refs.ruleForm.validateField('applyDepartmentSn')
      })
    },
    // 费用产生月
    expenseDateChange (v, d) {
      this.form.expenseDate = d
    },
    // 费用产生月禁止范围
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // 费用类型选择
    expenseChange (val, opts) {
      this.expenseTypes = val || []
      this.form.expenseType = val && val[0] ? val[0] : ''
      this.form.expenseType2 = val && val[1] ? val[1] : ''
      this.form.expenseType3 = val && val[2] ? val[2] : ''
      // 名称
      this.form.expenseTypeName = opts && opts[0] ? opts[0].name : ''
      this.form.expenseTypeName2 = opts && opts[1] ? opts[1].name : ''
      this.form.expenseTypeName3 = opts && opts[2] ? opts[2].name : ''
      // 校验规则
      this.$refs.ruleForm.clearValidate()
      this.setValidBrandType()
    },
    // 判断是否促销费用类型，必填品牌和分类
    setValidBrandType () {
      if (this.form.expenseTypeName == '促销费用') {
        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 = []
      }
    },
    //  附件上传
    changeAttach (file) {
      this.attachList = JSON.parse(file)
      this.attachList.map(item => {
        item.fileType = item.extName
      })
    },
    // 编辑时设置数据
    setDetail (data, from) {
      this.spinning = false
      this.disabled = false
      this.fromPage = from
      this.form = Object.assign(this.form, data)
      // 获取附件列表
      if (this.$refs.attachList) {
        this.form.expenseAccountFilesList = ''
        this.attachList = data.expenseAccountFilesList
        this.$refs.attachList.setFileList(this.attachList)
      }
      if (data.productTypeSn1) {
        this.productType = [data.productTypeSn1, data.productTypeSn2, data.productTypeSn3]
      }
      if (!data.productBrandSn) {
        this.form.productBrandSn = undefined
      }
      setTimeout(() => {
        this.expenseTypes = data.expenseType ? [this.form.expenseType, this.form.expenseType2, this.form.expenseType3] : []
      }, 500)
      this.setValidBrandType()
    },
    //  获取详情
    getDetail () {
      this.spinning = true
      this.disabled = true
      expenseAccountDetail({ expenseAccountSn: this.expenseAccountSn }).then(res => {
        if (res.status == 200) {
          this.setDetail(res.data)
        } else {
          this.$refs.ruleForm.resetFields()
        }
        this.spinning = false
        this.disabled = false
      })
    },
    // 保存基础信息
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(_this.form))
          form.expenseDate = form.expenseDate + '-01'
          form.expenseAccountFilesList = _this.attachList
          // 判断费用归属品类  最少要选择到2级或3级分类
          if (_this.form.productTypeSn1 && !_this.form.productTypeSn2) {
            _this.$message.warning('请选择归属分类(至少选择到2级或3级分类)')
            return false
          }
          _this.spinning = true
          // 从销售单转的费用，直接提交
          if (_this.fromPage == 'sales') {
            _this.$emit('expenseSaveOk', form, _this.fromPage)
            return false
          }
          // 从销售单转的费用,合并提交
          if (_this.fromPage == 'salesMearge') {
            _this.$emit('expenseSaveOk', form, _this.fromPage)
            return false
          }
          // 手动建的费用单
          expenseAccountSave(form).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(() => {
                if (_this.expenseAccountSn) {
                  _this.$emit('refashData')
                } else {
                  // 跳转到费用明细单页面
                  _this.$router.push({ name: 'expenseReimbursementEdit', params: { sn: res.data.expenseAccountSn } })
                }
                _this.spinning = false
                _this.cancel()
              }, 200)
            } else {
              _this.spinning = false
            }
          })
        } else {
          return false
        }
      })
    }
  },
  watch: {
    show (newValue, oldValue) {
      this.opened = newValue
      if (newValue) {
        this.pageInit()
      } else {
        this.retsetForm()
      }
    },
    itemSn (a, b) {
      this.expenseAccountSn = a
    }
  }
}
</script>
