<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="80%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="145px">
        <el-card class="box-card">
          <!-- 卡片头 -->
          <div slot="header" class="clearfix">
            <i class="el-icon-plus"/>
            <span>入库信息</span>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="资产编号" prop="propNo">
                  <el-input v-model="formData.propNo" placeholder="请输入资产编号"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资产名称" prop="propName">
                  <el-input v-model="formData.propName" placeholder="请输入资产名称"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="资产分类" prop="propCatg">
                  <el-select v-model="formData.propCatg" placeholder="请选择资产分类" class="customerSelectWidth">
                    <el-option v-for="dict in companyPropertyCatg" :key="dict.code"
                               :label="dict.name" :value="dict.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计使用年限" prop="useYear">
                  <el-input v-model="formData.useYear" placeholder="请输入预计使用年限" type="number"
                            class="customerInputWidth"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="价值类型" prop="costType">
                  <el-select v-model="formData.costType" placeholder="请选择价值类型" class="customerSelectWidth">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_COST_TYPE)" :key="dict.value"
                               :label="dict.label" :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资产状态" prop="propStatus">
                  <el-select v-model="formData.propStatus" placeholder="请选择资产状态" class="customerSelectWidth">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_PROP_STATUS)" :key="dict.value"
                               :label="dict.label" :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="资产数量" prop="propNum">
                  <el-input v-model="formData.propNum" placeholder="请输入资产数量" type="number" class="customerInputWidth"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资产原值（元）" prop="costTotal">
                  <el-input v-model="formData.costTotal" placeholder="请输入资产原值（元）" type="number"
                            class="customerInputWidth"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="品牌" prop="brand">
                  <el-input v-model="formData.brand" placeholder="请输入品牌"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="spec">
                  <el-input v-model="formData.spec" placeholder="请输入规格型号"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="生产厂家" prop="factory">
                  <el-input v-model="formData.factory" placeholder="请输入生产厂家"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出场序列号/编号" prop="serialNo">
                  <el-input v-model="formData.serialNo" placeholder="请输入出场序列号/编号"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="数量计量单位" prop="unit">
                  <el-input v-model="formData.unit" placeholder="请输入数量计量单位"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="取得日期" prop="getDate">
                  <el-date-picker clearable v-model="formData.getDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择取得日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="出厂日期" prop="prodDate">
                  <el-date-picker clearable v-model="formData.prodDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择出厂日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商" prop="supplier">
                  <el-input v-model="formData.supplier" placeholder="请输入供应商"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="维修/保养周期单位" prop="keepCycleType">
                  <el-select v-model="formData.keepCycleType" placeholder="请选择维修/保养周期单位" clearable class="customerSelectWidth">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.CYCLE_DICT)" :key="dict.value"
                               :label="dict.label" :value="dict.value" @blur="getNextKeepDate"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="维修/保养周期" prop="keepCycle">
                  <el-input v-model="formData.keepCycle" placeholder="请输入维修/保养周期" @blur="getNextKeepDate"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="上次维修/保养日期" prop="lastKeepDate">
                  <el-date-picker @blur="getNextKeepDate" clearable v-model="formData.lastKeepDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择上次维修/保养日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="下次维修/保养日期" prop="nextKeepDate">
                  <el-date-picker disabled clearable v-model="formData.nextKeepDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择下次维修/保养日期"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card class="box-card">
          <!-- 卡片头 -->
          <div slot="header" class="clearfix">
            <i class="el-icon-plus"/>
            <span>出库信息</span>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="启用日期" prop="openDate">
                  <el-date-picker clearable v-model="formData.openDate" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择启用日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="净值（元）" prop="netValue">
                  <el-input v-model="formData.netValue" placeholder="请输入净值（元）"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="使用人" prop="userId">
                  <el-select filterable v-model="formData.userId" placeholder="请选择使用人" clearable class="customerSelectWidth" :filter-method="searchOption">
                    <el-option v-for="item in options" :key="item.userId" :label="item.name" :value="item.userId">
                      <div class="options">
                        <span>姓名:{{ item.name }}</span>
                        <span>工号:{{ item.workNo }}</span>
                        <span>手机:{{ item.tel }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="存放位置" prop="posId">
                  <el-select v-model="formData.posId" clearable filterable placeholder="请选择存放位置" class="customerSelectWidth">
                    <el-option v-for="item in positionList" :key="item.id" :label="item.posName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="2">
              <el-col :span="12">
                <el-form-item label="凭证号" prop="voucherNo">
                  <el-input v-model="formData.voucherNo" placeholder="请输入凭证号"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-card class="box-card">
          <!-- 卡片头 -->
          <div slot="header" class="clearfix">
            <i class="el-icon-plus"/>
            <span>附件信息</span>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-form-item label="附件上传" prop="fileUrls">
              <file-upload v-model="formData.fileUrls"/>
            </el-form-item>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as PropertyApi from '@/api/company/property/property'
import FileUpload from '@/components/FileUpload'

export default {
  name: 'PropertyForm',
  components: {
    FileUpload
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        corpId: undefined,
        deptId: undefined,
        posId: undefined,
        userId: undefined,
        propNo: undefined,
        propName: undefined,
        propCatg: undefined,
        useYear: undefined,
        costType: undefined,
        propNum: undefined,
        costTotal: undefined,
        propStatus: undefined,
        brand: undefined,
        spec: undefined,
        factory: undefined,
        serialNo: undefined,
        unit: undefined,
        getDate: undefined,
        prodDate: undefined,
        supplier: undefined,
        openDate: undefined,
        netValue: undefined,
        voucherNo: undefined,
        keepCycleType: undefined,
        keepCycle: undefined,
        lastKeepDate: undefined,
        nextKeepDate: undefined,
        fileUrls: undefined
      },
      // 表单校验
      formRules: {
        propNo: [{required: true, message: '资产编号不能为空', trigger: 'blur'}],
        propName: [{required: true, message: '资产名称不能为空', trigger: 'blur'}],
        propCatg: [{required: true, message: '资产分类不能为空', trigger: 'blur'}],
        costType: [{required: true, message: '价值类型不能为空', trigger: 'blur'}],
        propStatus: [{required: true, message: '资产状态不能为空', trigger: 'blur'}],
        openDate: [{required: true, message: '启用日期不能为空', trigger: 'blur'}],
        netValue: [{required: true, message: '净值不能为空', trigger: 'blur'}],
        voucherNo: [{required: true, message: '凭证号不能为空', trigger: 'blur'}],
        userId: [{required: true, message: '使用人不能为空', trigger: 'blur'}],
        posId: [{required: true, message: '存放位置不能为空', trigger: 'blur'}],
        propNum: [{required: true, message: '资产数量不能为空', trigger: 'blur'}],
        costTotal: [{required: true, message: '资产原值不能为空', trigger: 'blur'}],
        keepCycleType: [{required: true, message: '维修/保养周期单位不能为空', trigger: 'blur'}],
        keepCycle: [{required: true, message: '维修/保养周期不能为空', trigger: 'blur'}],
        lastKeepDate: [{required: true, message: '上次维修/保养日期不能为空', trigger: 'blur'}],
        nextKeepDate: [{required: true, message: '下次维修/保养日期不能为空', trigger: 'blur'}],
      },
      companyPropertyCatg: [],
      staffList: [],
      positionList: [],
      options: [],
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id, companyPropertyCatg, staffList, positionList) {
      this.dialogVisible = true
      this.reset()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true
        try {
          const res = await PropertyApi.getProperty(id)
          this.formData = res.data
          this.formData.userId = parseInt(this.formData.userId)
        } finally {
          this.formLoading = false
        }
      }
      this.dialogTitle = id ? '修改企业管理-资产' : '新增企业管理-资产'
      this.companyPropertyCatg = companyPropertyCatg
      this.staffList = staffList
      this.options = this.staffList
      this.positionList = positionList
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs['formRef'].validate()
      this.formLoading = true
      try {
        const data = this.formData
        // 修改的提交
        if (data.id) {
          await PropertyApi.updateProperty(data)
          this.$modal.msgSuccess('修改成功')
          this.dialogVisible = false
          this.$emit('success')
          return
        }
        // 添加的提交
        await PropertyApi.createProperty(data)
        this.$modal.msgSuccess('新增成功')
        this.dialogVisible = false
        this.$emit('success')
      } finally {
        this.formLoading = false
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        corpId: undefined,
        deptId: undefined,
        posId: undefined,
        userId: undefined,
        propNo: undefined,
        propName: undefined,
        propCatg: undefined,
        useYear: undefined,
        costType: undefined,
        propNum: undefined,
        costTotal: undefined,
        propStatus: undefined,
        brand: undefined,
        spec: undefined,
        factory: undefined,
        serialNo: undefined,
        unit: undefined,
        getDate: undefined,
        prodDate: undefined,
        supplier: undefined,
        openDate: undefined,
        netValue: undefined,
        voucherNo: undefined,
        keepCycleType: undefined,
        keepCycle: undefined,
        lastKeepDate: undefined,
        nextKeepDate: undefined,
        fileUrls: undefined
      }
      this.resetForm('formRef')
    },
    // 计算下次维修、保养时间
    getNextKeepDate(){
      if (!(this.formData.keepCycleType && this.formData.keepCycle && this.formData.lastKeepDate)){
        this.$refs.formRef.validateField('keepCycleType');
        this.$refs.formRef.validateField('keepCycle');
        this.$refs.formRef.validateField('lastKeepDate');
        return
      }
      this.$refs.formRef.validateField('keepCycleType');
      const tempDate = new Date(this.formData.lastKeepDate)
      const chooseType =this.formData.keepCycleType;
      const num = parseInt(this.formData.keepCycle)
      switch (chooseType) {
        case '01':
          tempDate.setFullYear(tempDate.getFullYear() + num);
          break;
        case '02':
          tempDate.setMonth(tempDate.getMonth() + num);
          break;
        case '03':
          tempDate.setDate(tempDate.getDate() + num);
          break;
        default:
          throw new Error('超出预期了，只能是年、月、天');
      }
      this.formData.nextKeepDate = new Date(tempDate)
    },
    searchOption(val) {
      this.options = this.staffList.filter(item => (
        item.name.toLowerCase().includes(val.toLowerCase()) ||
        item.workNo.includes(val) ||
        item.tel.includes(val)
      ))
    }
  }
}
</script>

<style scoped lang="scss">
.customerInputWidth {
  width: 50%;
}

.customerSelectWidth {
  width: 100%;
}

.box-card {
  margin-bottom: 10px;
}
.options{
  display: flex;
  justify-content: space-between;
}
</style>
