<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 :disabled="!!formData.id" clearable v-model="formData.dealDate" type="date"
                                  value-format="yyyy-MM-dd"
                                  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 v-if="!formData.id" 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" width="180"/>
              <el-table-column label="资产名称" prop="propName" align="center" width="180"/>
              <el-table-column label="调入企业" prop="corpId" align="center" width="180">
                <template #default="{ row }">
                  <el-select v-model="row.corpId" placeholder="请选择调入企业" clearable size="small"
                             @change="getOtherList(row)"
                  >
                    <el-option v-for="item in companyList" :key="item.id"
                               :label="item.corpName"
                               :value="item.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <!-- TODO 修改回显有问题 -->
              <el-table-column label="调入使用人" prop="userId" align="center" width="180">
                <template #default="{ row }">
                  <el-select v-model="row.userId" placeholder="请选择使用人" clearable size="small">
                    <el-option v-for="item in staffList" :key="item.userId"
                               :label="item.name"
                               :value="item.userId"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="调入存放地" prop="posId" align="center" width="180">
                <template #default="{ row }">
                  <el-select v-model="row.posId" placeholder="请选择调入企业" clearable size="small">
                    <el-option v-for="item in positionList" :key="item.id"
                               :label="item.posName"
                               :value="item.id"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="propNum" width="180">
                <template #default="{ row }">
                  {{ row.propNum + ' ' + row.unit }}
                </template>
              </el-table-column>
              <el-table-column label="价格" align="center" prop="netValue" width="180"/>
              <el-table-column label="取得方式" align="center" prop="dealWay" width="180">
                <template #default="{ row }">
                  <el-select v-model="row.dealWay" placeholder="请选择取得方式" clearable size="small">
                    <el-option v-for="dict in getDictDatas(DICT_TYPE.PROPERTY_GET_WAY)" :key="dict.value"
                               :label="dict.label"
                               :value="dict.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" width="180">
                <template #default="{ row }">
                  <el-input type="textarea" v-model="row.remark"/>
                </template>
              </el-table-column>
              <el-table-column v-if="!formData.id" fixed="right" label="操作" align="center"
                               class-name="small-padding fixed-width" width="150"
              >
                <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 v-if="!formData.id" 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="propNum" width="150"/>
        <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 * as PropertyDealItemApi from '@/api/company/property/propertydealitem'
import { createUUID } from '@/utils/createUniqueCode'
import * as PropertyDealApi from '@/api/company/property/propertydeal'
import * as PropertyApi from '@/api/company/property/property'
import { getCompanyList } from '@/api/base/company'
import { getStaffListByCorpId } from '@/api/company/staff'
import { getPositionListByCorpId } from '@/api/company/property/position'

export default {
  name: 'PropertyDealChangeForm',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        dealNo: undefined,
        dealDate: undefined,
        dataType: '01',
        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,
      companyList: [],
      staffList: [],
      positionList: []
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.reset()
      // 修改时，设置数据
      if (id) {
        this.formLoading = true
        this.formData.id = id
        try {
          const res = await PropertyDealItemApi.getPropertyDealItem(id)
          const propertyDeal = res.data.propertyDeal
          this.formData.dealNo = propertyDeal.dealNo
          this.formData.dealDate = propertyDeal.dealDate
          this.formData.dataType = propertyDeal.dataType
          this.formData.dealId = propertyDeal.id
          const property = res.data.property
          property.dealWay = res.data.dealWay
          await this.getOtherList(property.corpId)
          property.userId = parseInt(property.userId)
          this.formData.propList.push(property)
        } finally {
          this.formLoading = false
        }
      }
      if (!id) this.formData.dealNo = createUUID()
      this.dialogTitle = id ? '修改资产变动单' : '新增资产变动单'
      await this.listCompany()
      this.dialogVisible = true
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        dealNo: undefined,
        dealDate: undefined,
        dataType: '01',
        propList: []
      }
      this.resetForm('formRef')
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs['formRef'].validate()
      // 校验资产列表
      const flag = await this.validatePropList()
      if (flag) {
      this.formLoading = true
        try {
          const data = this.formData
          // 修改的提交
          if (data.id) {
            const newData = {
              id: data.id,
              dealWay: data.propList[0].dealWay,
              dealId: data.dealId,
              propertyId: data.propList[0].id,
              remark: data.propList[0].remark,
              corpId: data.propList[0].corpId,
              userId: data.propList[0].userId,
              posId: data.propList[0].posId,
            }
            await PropertyDealItemApi.updatePropertyDealItemChange(newData)
            this.$modal.msgSuccess('修改成功')
            this.dialogVisible = false
            this.$emit('success')
            return
          }
          // 添加的提交
          await PropertyDealApi.createPropertyDealChange(data)
          this.$modal.msgSuccess('新增成功')
          this.dialogVisible = false
          this.$emit('success')
        } finally {
          this.formLoading = false
        }
      }
    },
    /** 查询列表 */
    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
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    chooseProp(row) {
      this.chooseDisable = false
      const newRow = {
        ...row,
        dealWay: null,
        remark: null
      }
      newRow.corpId = null
      newRow.userId = null
      newRow.posId = null
      this.formData.propList.push(newRow)
    },
    deleteProp(index) {
      this.formData.propList.splice(index, 1)
    },
    async listCompany() {
      const res = await getCompanyList()
      this.companyList = res.data
    },
    async listStaff(id) {
      const res = await getStaffListByCorpId(id)
      this.staffList = res.data
    },
    async listPosition(id) {
      const res = await getPositionListByCorpId(id)
      this.positionList = res.data
    },
    async getOtherList(row) {
      if (row instanceof Object){
        row.posId = null
        row.userId = null
        await this.listStaff(row.corpId)
        await this.listPosition(row.corpId)
        return
      }
      await this.listStaff(row)
      await this.listPosition(row)
    },
    async validatePropList() {
      const tempList = this.formData.propList
      if (!tempList || tempList.length === 0) {
        this.$modal.msgError('资产列表不能为空')
        return false
      } else {
        const hasEmptyCorpId = tempList.some(item => !item.corpId)
        const hasEmptyUserId = tempList.some(item => !item.userId)
        const hasEmptyPosId = tempList.some(item => !item.posId)
        const hasEmptyDealWay = tempList.some(item => !item.dealWay)
        if (hasEmptyCorpId) {
          this.$modal.msgError('调入企业不能为空')
          return false
        }
        if (hasEmptyUserId) {
          this.$modal.msgError('调入使用人不能为空')
          return false
        }
        if (hasEmptyPosId) {
          this.$modal.msgError('调入存放地不能为空')
          return false
        }
        if (hasEmptyDealWay) {
          this.$modal.msgError('取得方式不能为空')
          return false
        }
        return true
      }
    }
  }
}
</script>

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