<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="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-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 { expenseAccountDetail, expenseAccountSave } from '@/api/expenseManagement.js'
export default {
  name: 'BaseDataModal',
  components: { VSelect, Upload, STable, department, employee, expenseType },
  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: [], // 费用类型值
      form: {
        applyPersonSn: undefined, // 申请人
        applyDepartmentSn: undefined, //  申请部门
        expenseType: undefined, //  费用类型1
        expenseType2: undefined, //  费用类型2
        expenseType3: undefined, // 费用类型3
        expenseTypeName: undefined, //  费用类型1
        expenseTypeName2: undefined, //  费用类型2
        expenseTypeName3: undefined, // 费用类型3
        expenseDate: moment().locale('zh-cn').format('YYYY-MM'), //  费用产生月
        title: '', // 主题
        content: '' // 费用说明
      },
      rules: {
        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' }
        ]
      }
    }
  },
  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
        expenseDate: moment().locale('zh-cn').format('YYYY-MM'), //  费用产生月
        title: '', // 主题
        content: '' // 费用说明
      }
      this.attachList = []
      this.form.expenseAccountFilesList = ''
      this.$refs.attachList.setFileList('')
      this.$refs.ruleForm.resetFields()
      this.expenseTypes = []
    },
    // 申请人员
    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 : ''
    },
    //  附件上传
    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)
      }
      setTimeout(() => {
        this.expenseTypes = data.expenseType ? [this.form.expenseType, this.form.expenseType2, this.form.expenseType3] : []
      }, 500)
    },
    //  获取详情
    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
          // console.log(form)
          _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>
