<template>
  <div class="view-table-content" style="width: 80%; margin: 0 auto">
    <div>
      <el-descriptions class="detail" :column="4">
        <el-descriptions-item label="机型">{{ smTaskForm.aircraftModel }}</el-descriptions-item>
        <el-descriptions-item label="编目">{{ smTaskForm.aircraftId }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ smTaskForm.name }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ smTaskForm.specialty }}</el-descriptions-item>
        <el-descriptions-item label="任务编码">{{ smTaskForm.taskCode }}</el-descriptions-item>
        <el-descriptions-item label="周期">{{ smTaskForm.periodTime }}</el-descriptions-item>
        <el-descriptions-item label="剩余时间">{{ smTaskForm.remainTime }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ smTaskForm.headName }}</el-descriptions-item>
        <el-descriptions-item label="系统">{{ smTaskForm.systemName }}</el-descriptions-item>
        <el-descriptions-item label="任务内容">{{ smTaskForm.contents }}</el-descriptions-item>
      </el-descriptions>
      <el-tabs type="card" v-model="tabActiveName" style="margin-top: 30px">
        <el-tab-pane label="资源分配" name="first">
          <div class="view-dataType-title">
            <div class="view-dataType-title-btn">
              <el-button type="success" @click="openDialog()">新增</el-button>
              <el-button type="warning" @click="remove(tableCheckItems)" :disabled="tableCheckItems.length == 0">删除</el-button>
            </div>
          </div>
          <div class="view-dataType-table">
            <LTable ref="table" @selection-change="selection" :defaultFetch="false" :fetch="fetch" :columns="columns" :dataSource="tableData" :options="options" :pagination="tableRequset"></LTable>
          </div>
        </el-tab-pane>
        <el-tab-pane label="任务派遣" name="second">
          <div class="view-dataType-title">
            <div class="view-dataType-title-btn">
              <el-button type="success" @click="openDialog2()">新增</el-button>
              <el-button type="warning" @click="remove(tableCheckItems2)" :disabled="tableCheckItems2.length == 0">删除</el-button>
            </div>
          </div>
          <div class="view-dataType-table">
            <LTable ref="table2" @selection-change="selection2" :defaultFetch="false" :fetch="fetch2" :columns="columns2" :dataSource="tableData2" :options="options" :pagination="tableRequset2"></LTable>
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :before-close="handleClose">
        <el-form ref="form" :model="form" label-width="80px" style="height: 400px; overflow-y: scroll">
          <!-- <el-form-item label="任务" prop="taskId">
            <el-input v-model="form.taskId" placeholder="请输入任务" />
          </el-form-item> -->
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="型号" prop="modelNumber">
            <el-input v-model="form.modelNumber" placeholder="请输入型号" />
          </el-form-item>
          <el-form-item label="设备编码" prop="deviceCode">
            <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <!-- <el-input v-model="form.type" placeholder="请输入类型" /> -->
            <el-select v-model="form.type" placeholder="请选择类型">
              <el-option label="设备" value="设备"></el-option>
              <el-option label="备件" value="备件"></el-option>
              <el-option label="耗材" value="耗材"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input v-model="form.quantity" placeholder="请输入数量" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="dialogTitle2" :visible.sync="dialogVisible2" width="600px" :before-close="handleClose2">
        <el-form ref="form2" :model="form2" label-width="80px" style="height: 350px; overflow-y: scroll">
          <!-- <el-form-item label="任务" prop="taskId">
            <el-input v-model="form.taskId" placeholder="请输入任务" />
          </el-form-item> -->
          <el-form-item label="人员" prop="deviceName">
            <el-input v-model="form2.personnel" placeholder="请输入人员" />
          </el-form-item>
          <el-form-item label="岗位" prop="position">
            <el-input v-model="form2.position" placeholder="请输入岗位" />
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input v-model="form2.quantity" placeholder="请输入数量" />
          </el-form-item>
          <el-form-item label="职责" prop="duties">
            <el-input v-model="form2.duties" placeholder="请输入职责" />
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form2.remarks" placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="submit2">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getResourceAllocation, addResourceAllocation, updateResourceAllocation, removeResourceAllocation } from '@/api/als/resourceAllocation'
import { getPersonnelAllocation, addPersonnelAllocation, updatePersonnelAllocation, removePersonnelAllocation } from '@/api/als/personnelAllocation'
import { getAircaftModelAll, getAircaftCatalogAll } from '@/api/als/aircraft'
import { updateSmTask, getSmTaskDetail } from '@/api/als/smTask'
import { deepClone, debounce } from '@/utils/index'
import { flattenTree } from '../utils/common'

export default {
  name: 'SMTaskDetails',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogTitle: '新增',
      dialogTitle2: '新增',
      dialogVisible: false,
      dialogVisible2: false,
      keyWord: '',
      searchValue: '',
      columns: [
        {
          prop: 'deviceName',
          label: '名称'
        },
        {
          prop: 'modelNumber',
          label: '型号'
        },
        {
          prop: 'deviceCode',
          label: '设备编码'
        },

        {
          prop: 'type',
          label: '类型'
        },
        {
          prop: 'quantity',
          label: '数量'
        },
        {
          prop: 'remarks',
          label: '备注'
        },

        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '编辑',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.handUpdate(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([row])
              }
            }
          ]
        }
      ],
      columns2: [
        {
          prop: 'personnel',
          label: '人员'
        },
        {
          prop: 'position',
          label: '岗位'
        },
        {
          prop: 'quantity',
          label: '数量'
        },

        {
          prop: 'duties',
          label: '职责'
        },
        {
          prop: 'remarks',
          label: '备注'
        },

        {
          button: true,
          label: '操作',
          width: '240px',
          group: [
            {
              name: '编辑',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.handUpdate2(row)
              }
            },
            {
              name: '删除',
              type: 'text',
              round: false,
              plain: false,
              onClick: (row, index, scope) => {
                this.remove([row])
              }
            }
          ]
        }
      ],
      options: {
        stripe: true, // 斑马纹
        mutiSelect: true, // 多选框
        index: false, // 显示序号， 多选则 mutiSelect
        loading: false, // 表格动画
        initTable: false, // 是否一挂载就加载数据
        border: true,
        height: 'calc(100vh - 480px)'
      },
      tableCheckItems: [],
      tableCheckItems2: [],
      tableData: [],
      tableRequset: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableRequset2: {
        total: 0,
        pageIndex: 1,
        pageSize: 10,
        searchValue: ''
      },
      tableData2: [],
      form: {
        id: '',
        taskId: '',
        deviceName: '',
        serialNumber: '',
        deviceCode: '',
        type: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      form2: {
        id: '',
        taskId: '',
        personnel: '',
        position: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      },
      debounceFn: debounce(this.fetch, 500),
      smTaskId: '',
      smTaskForm: [],
      tabActiveName: 'first'
    }
  },
  watch: {
    keyWord() {
      this.tableRequset.pageIndex = 1
      this.debounceFn()
    },
    tabActiveName: {
      handler(val) {
        if (val === 'first') {
          this.getResourceAllocationAPI({ taskId: this.smTaskId })
        } else {
          this.getPersonnelAllocationAPI({ taskId: this.smTaskId })
        }
      }
    }
  },
  mounted() {
    this.getSmTaskDetailAPI()
  },
  methods: {
    async getSmTaskDetailAPI() {
      try {
        this.smTaskId = this.$route.query.smTaskId
        this.form.taskId = this.smTaskId
        const { data } = await getSmTaskDetail(this.smTaskId)

        const { data: data1 } = await getAircaftModelAll({
          aircaftTypeCode: '',
          aircaftTypeId: '',
          queryParam: ''
        })
        this.aircaftModelAll = data1
        const { data: data2 } = await getAircaftCatalogAll({
          keyWord: '',
          aircaftModelIdList: []
        })
        this.aircaftCatalogAll = flattenTree(data2)

        data.aircraftModel = this.aircaftModelAll.find((item) => data.aircraftModel === item.aircaftModelId)?.aircaftModelName
        data.aircraftId = this.aircaftCatalogAll.find((item) => data.aircraftId === item.aircaftCatalogId)?.aircaftCatalogCode
        this.smTaskForm = data
        this.getResourceAllocationAPI({ taskId: this.smTaskId })
      } catch (error) {}
    },

    async removeResourceAllocationAPI(params) {
      try {
        const { code } = await removeResourceAllocation(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getResourceAllocationAPI({ taskId: this.smTaskId })
          this.handleClose()
        }
      } catch (error) {}
    },

    async removePersonnelAllocationAPI(params) {
      try {
        const { code } = await removePersonnelAllocation(params)
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          await this.getPersonnelAllocationAPI({ taskId: this.smTaskId })
          this.handleClose()
        }
      } catch (error) {}
    },

    async getResourceAllocationAPI(params) {
      if (this.$refs.table) this.$refs.table.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset
      const {
        data: { list, total }
      } = await getResourceAllocation({ pageSize, pageNum: pageIndex, ...params })
      this.tableData = list
      this.tableRequset.total = total
    },

    async getPersonnelAllocationAPI(params) {
      if (this.$refs.table2) this.$refs.table2.clearSelection()
      const { keyWord } = this
      const { pageSize, pageIndex } = this.tableRequset2
      const {
        data: { list, total }
      } = await getPersonnelAllocation({ pageSize, pageNum: pageIndex, ...params })
      this.tableData2 = list
      this.tableRequset2.total = total
    },

    fetch() {
      this.getResourceAllocationAPI({ taskId: this.smTaskId })
    },

    fetch2() {
      this.getPersonnelAllocationAPI({ taskId: this.smTaskId })
    },

    async addResourceAllocationAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addResourceAllocation({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          await updateSmTask({ id: this.smTaskId, status: 1, version: this.smTaskForm.version })
          this.getResourceAllocationAPI({ taskId: this.smTaskId })
        }
      } catch (error) {}
    },

    async addPersonnelAllocationAPI() {
      try {
        delete this.form.aircaftModelName
        const { code } = await addPersonnelAllocation({ ...this.form2 })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose2()
          const res = await getSmTaskDetail(this.smTaskId)
          await updateSmTask({ id: this.smTaskId, status: 1, version: res.data.version })
          this.getPersonnelAllocationAPI({ taskId: this.smTaskId })
        }
      } catch (error) {}
    },

    async updateResourceAllocationAPI() {
      try {
        const { code } = await updateResourceAllocation({ ...this.form })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose()
          this.getResourceAllocationAPI({ taskId: this.smTaskId })
        }
      } catch (error) {}
    },

    async updatePersonnelAllocationAPI() {
      try {
        const { code } = await updatePersonnelAllocation({ ...this.form2 })
        if (code === 200) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.handleClose2()
          this.getPersonnelAllocationAPI({ taskId: this.smTaskId })
        }
      } catch (error) {}
    },

    openDialog() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
      this.form.taskId = this.smTaskId
    },

    openDialog2() {
      this.dialogTitle2 = '新增'
      this.dialogVisible2 = true
      this.form2.taskId = this.smTaskId
      // this.form.aircraftId = { taskId: this.smTaskId }
      // this.form.aircraftType = this.currentNode.label
    },

    handleClose() {
      this.dialogVisible = false
      this.form = {
        id: '',
        taskId: '',
        deviceName: '',
        serialNumber: '',
        deviceCode: '',
        type: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

    handleClose2() {
      this.dialogVisible2 = false
      this.form2 = {
        id: '',
        taskId: '',
        personnel: '',
        position: '',
        quantity: '',
        remarks: '',
        tenantId: '',
        version: '',
        delFlag: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: ''
      }
    },

    handUpdate(row) {
      this.dialogTitle = '编辑'
      this.form = deepClone(row)
      this.dialogVisible = true
    },

    handUpdate2(row) {
      this.dialogTitle2 = '编辑'
      this.form2 = deepClone(row)
      this.dialogVisible2 = true
    },

    submit() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updateResourceAllocationAPI()
          break
        case '新增':
          this.addResourceAllocationAPI()
          break
      }
    },

    submit2() {
      switch (this.dialogTitle) {
        case '编辑':
          this.updatePersonnelAllocationAPI()
          break
        case '新增':
          this.addPersonnelAllocationAPI()
          break
      }
    },

    selection(val) {
      this.tableCheckItems = val
    },

    selection2(val) {
      this.tableCheckItems2 = val
    },

    remove(row) {
      this.$confirm('是否删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tabActiveName === 'first' ? this.removeResourceAllocationAPI(row.map((e) => e.id)) : this.removePersonnelAllocationAPI(row.map((e) => e.id))
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../index.scss';

.detail {
  .el-descriptions {
    margin-bottom: 20px;
  }

  .el-descriptions-item__label .is-bordered-label,
  .el-descriptions__body {
    background-color: transparent !important;
  }
}
</style>
