<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="100px">
        <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="dealNo">
                  <el-input disabled v-model="formData.dealNo"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处置时间" prop="dealDate">
                  <el-date-picker clearable v-model="formData.dealDate" type="date" value-format="timestamp"
                                  placeholder="选择处置/变动日期"
                  />
                </el-form-item>
                <el-form-item v-show="false" label="数据类型" prop="dataType">
                  <el-select v-model="queryParams.dataType" placeholder="请选择处置方式" clearable size="small">
                    <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PROPERTY_DATA_TYPE)" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </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>
            <el-button type="primary" style="float: right" @click="getList">选择资产</el-button>
          </div>
          <!-- 卡片内容 -->
          <div>
            <el-table :data="formData.propList" :stripe="true" :show-overflow-tooltip="true">
              <el-table-column label="序号" align="center" prop="num">
                <template #default="{ $index }">
                  {{ $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="资产编号" prop="propNo" align="center" />
              <el-table-column label="资产名称" prop="propName" align="center" />
              <el-table-column label="价值类型" align="center" prop="costType" />
              <el-table-column label="资产原值(元)" align="center" prop="costTotal" />
              <el-table-column label="净值(元)" align="center" prop="netValue" />
              <el-table-column label="存放位置" align="center" prop="posName" width="150px"/>
              <el-table-column label="处置方式" align="center" prop="dealWay">
                <template #default="{ row }">
                  <el-select v-model="row.dealWay" placeholder="请选择处置方式" clearable size="small">
                    <el-option v-for="dict in getDictDatas(DICT_TYPE.COMPANY_DEAL_WAY)" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="200">
                <template v-slot="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteProp(scope.$index)"
                             >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择资产" :visible.sync="chooseDisable" width="60%" v-dialogDrag append-to-body>
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="资产名称" prop="propName">
          <el-input v-model="queryParams.propName" placeholder="请输入资产名称" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="资产编号" prop="propNo">
          <el-input v-model="queryParams.propNo" placeholder="请输入资产编号" clearable @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="序号" align="center" prop="num">
          <template slot-scope="scope">
          <span style="margin-left: 10px">{{
              queryParams.pageSize * (queryParams.pageNo - 1) + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="资产名称" align="center" prop="propName" width="150px"/>
        <el-table-column label="存放位置" align="center" prop="posName" width="150px"/>
        <el-table-column label="资产编号" align="center" prop="propNo" width="150px"/>
        <el-table-column label="价值类型" align="center" prop="costType" width="150px">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.COMPANY_COST_TYPE" :value="scope.row.costType"/>
          </template>
        </el-table-column>
        <el-table-column label="资产原值（元）" align="center" prop="costTotal"width="150px"/>
        <el-table-column label="资产状态" align="center" prop="propStatus" width="150px">
          <template v-slot="scope">
            <dict-tag :type="DICT_TYPE.COMPANY_PROP_STATUS" :value="scope.row.propStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="净值（元）" align="center" prop="netValue" width="150px"/>
        <el-table-column label="使用人" align="center" prop="staffName" width="150px" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="150px">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-check" @click="chooseProp(scope.row)"
            >选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"
      />
    </el-dialog>
  </div>
</template>

<script>

import { createUUID } from '@/utils/createUUID'
import * as PropertyApi from '@/api/company/property/property'
import * as PropertyDealApi from '@/api/company/property/propertydeal'

export default {
  name: 'PropertyDealDisposalForm',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        dealNo: undefined,
        dealDate: undefined,
        dataType: "02",
        propList: []
      },
      // 表单校验
      formRules: {
        dealDate: [{required: true, message: "处置日期不能为空", trigger: 'blur'}],
      },
      chooseDisable: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        corpId: null,
        deptId: null,
        posId: null,
        userId: null,
        propNo: null,
        propName: null,
        propCatg: null,
        useYear: null,
        costType: null,
        propNum: null,
        costTotal: null,
        propStatus: null,
        brand: null,
        spec: null,
        factory: null,
        serialNo: null,
        unit: null,
        getDateArray: [],
        prodDate: [],
        supplier: null,
        openDateArray: [],
        netValue: null,
        voucherNo: null,
        keepCycleType: null,
        keepCycle: null,
        lastKeepDate: [],
        nextKeepDate: [],
      },
      // 显示搜索条件
      showSearch: true,
      list: [],
      total: 0,
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true
      this.reset()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true
        try {
          // const res = await PropertyDealApi.getPropertyDeal(id);
          // this.formData = res.data;
          this.dialogTitle = '修改资产处置单'
        } finally {
          this.formLoading = false
        }
      }
      this.formData.dealNo = createUUID()
      this.dialogTitle = '新增资产处置单'
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        dealNo: undefined,
        dealDate: undefined,
        dataType: "02",
        propList: []
      }
      this.resetForm('formRef')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true
        this.chooseDisable = true
        const res = await PropertyApi.getPropertyPage(this.queryParams)
        this.list = res.data.records
        this.list = this.list.filter(item => !this.formData.propList.map(i => i.id).includes(item.id))
        this.total = res.data.total
      } finally {
        this.loading = false
      }
    },
    chooseProp(row){
      this.chooseDisable = false;
      const newRow = {
        ...row,
        dealWay: null,
      }
      this.formData.propList.push(newRow)
    },
    deleteProp(index){
      this.formData.propList.splice(index, 1)
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      // 校验资产列表
      const flag = await this.validatePropList();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await PropertyDealApi.updatePropertyDeal(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await PropertyDealApi.createPropertyDeal(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    async validatePropList() {
      const tempList = this.formData.propList
      if (!tempList || tempList.length === 0) {
        this.$modal.msgError('资产列表不能为空')
        return false
      } else {
        const hasEmptyDealWay = tempList.some(item => !item.dealWay);
        if (hasEmptyDealWay) {
          this.$modal.msgError('处置方式不能为空')
          return false;
        } else {
          return true
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.box-card {
  margin-bottom: 10px;
}
</style>
