<template>
  <div class="page-container column-container">
    <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="仪器室名称：" prop="chamberName">
        <el-input v-model="queryParams.chamberName" placeholder="请输入仪器室名称" style="width: 144px" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="list-btns-container">
      <el-button type="primary" icon="Plus" @click="addNewChamber"
        v-hasPermi="['business:inspectionChamber:add']">新增</el-button>
      <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()"
        v-hasPermi="['business:inspectionChamber:remove']">
        删除
      </el-button>
    </div>

    <!-- 列表区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table v-loading="loading" :data="processList" height="100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="48" align="center" />
          <el-table-column label="行号" type="index" width="50" align="center" />
          <el-table-column label="仪器室名称" width="100" align="center" prop="chamberName">
            <template #default="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.chamberName }}</div>
              <el-input v-else v-model.trim="scope.row.chamberName" size="small" placeholder="仪器室名称" />
            </template>
          </el-table-column>
          <el-table-column label="仪器室编号" width="100" align="center" prop="chamberCode">
            <template #default="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.chamberCode }}</div>
              <el-input v-else v-model.trim="scope.row.chamberCode" size="small" placeholder="仪器室编号" />
            </template>
          </el-table-column>
          <el-table-column label="负责车间" width="400" align="center" prop="workShops">
            <template #default="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.workShops }}</div>
              <el-select v-else v-model="scope.row.workShopIds" size="small" multiple filterable reserve-keyword
                collapse-tags :max-collapse-tags="3" collapse-tags-tooltip placeholder="请选择车间" style="width: 100%;"
                @change="(arg) => handleWorkshopChange(arg, scope.row)">
                <el-option v-for=" item in workShops" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" header-align="center">
            <template #default="scope">
              <div v-if="!scope.row.editStatus">{{ scope.row.remark }}</div>
              <el-input v-else v-model.trim="scope.row.remark" size="small" placeholder="备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <el-button v-if="!scope.row.editStatus && checkPermi(['business:inspectionChamber:edit'])" link
                type="warning" icon="Edit"
                @click="() => { scope.row.editStatus = !scope.row.editStatus }">编辑</el-button>
              <el-button v-if="!scope.row.editStatus && checkPermi(['business:inspectionChamber:remove'])" link
                type="danger" icon="Delete" @click="handleDelete(scope.row, scope.$index)">删除</el-button>
              <el-button
                v-if="scope.row.editStatus && checkPermi(['business:inspectionChamber:edit', 'business:inspectionChamber:add'])"
                link type="warning" icon="Finished" @click="handleSave(scope.row)">保存</el-button>
              <el-button v-if="scope.row.editStatus" link type="warning" icon="Close"
                @click="() => { scope.row.editStatus = !scope.row.editStatus }">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 新增工序表单 -->
    <!-- <chamber-form ref="processRef" @handleSaveSuccess="handleRefreshProcess" /> -->
  </div>
</template>

<script setup name="Process">
import { listInspectionChamber, delInspectionChamber, addInspectionChamber, updateInspectionChamber } from '@/api/business/inspectionChamber'
import { listWorkshop } from '@/api/business/workshop'
// import { checkPermi } from '@/utils/permission.js'
// import { getP2Process } from "@/api/business/p2.js";
import useUserStore from '@/store/modules/user'
import chamberForm from './form'
const { proxy } = getCurrentInstance()
/** 字典数组区 */
const { process_status } = proxy.useDict('process_status')
/** 标准工序*/
const processList = ref([])
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const workShops = ref([])
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  code: '',
  name: ''
})

onMounted(() => {
  getList()
  getWorkShops()
})
/***********************  方法区  ****************************/

/** 查询标准工序管理列表 */
function getList() {
  loading.value = false
  listInspectionChamber(queryParams.value).then((response) => {
    processList.value = response.rows.map(v => ({ ...v, editStatus: false }))
    total.value = response.total
    loading.value = false
  })
}

function getWorkShops() {
  listWorkshop({}).then(res => {
    workShops.value = res.rows
    // console.log(workShops.value)
  })
}

function addNewChamber() {
  processList.value.push({ editStatus: true })
}

/** 搜索按钮操作 */
function handleRefreshProcess() {
  queryParams.value.pageNum = 1
  getList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleShowChamberDialog(id) {
  proxy.$refs.processRef.open(id)
}

/** 删除按钮操作 */
function handleDelete(row, index) {
  if (row != null && row.id == null) {
    processList.value.splice(index, 1)
  } else {
    const _ids = row ? row.id : ids.value
    proxy.$modal
      .confirm('是否确认删除选中的数据项？')
      .then(function () {
        return delInspectionChamber(_ids)
      })
      .then(() => {
        proxy.$modal.msgSuccess('删除成功！')
        getList()
      })
      .catch(() => { })
  }
}

function checkPermi(permissionDatas) {
  const permissions = useUserStore().permissions
  const all_permission = "*:*:*";
  const hasPermission = permissions.some(permission => {
    return all_permission === permission || permissionDatas.includes(permission)
  })
  return hasPermission;
}

function handleWorkshopChange(arg, row) {
  // console.log(arg, row)
  const includes = workShops.value.filter(v => arg.includes(v.id))
  // console.log(includes)
  row.workShops = includes.map(e => e.name).join(',')
  // console.log(includes.map(e => e.name).join(','))
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery()
}

function handleSave(row) {
  // 判断是否填写仪器室名称
  if (row.chamberName == null || row.chamberName == '') {
    proxy.$modal.msgError('请输入仪器室名称')
    return
  }
  // if (row.chamberCode == null || row.chamberCode == '') {
  //   proxy.$modal.msgError('请输入仪器室编号')
  //   return
  // }
  // 判断是否填写仪器室编号
  if (row.id == null) {
    addInspectionChamber(row).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('保存成功')
        getList()
      } else {
        proxy.$modal.msgError(res.msg)
      }
    })
  } else {
    updateInspectionChamber(row).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('保存成功')
        getList()
      } else {
        proxy.$modal.msgError(res.msg)
      }
    })
  }
}
</script>
