<template>
  <div class="page-container row-container">
    <!-- 左侧区域 -->
    <section class="list-part-container" style="flex: 2">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryDeptParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="车间管理" />
        <el-form-item>
          <el-button v-hasPermi="['business:workshop:add']" type="primary" icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item label="车间名称：" prop="name">
          <el-input v-model.trim="queryParams.name" placeholder="请输入车间名称" @keydown.enter.prevent
            @keyup.enter="handleSearch" clearable style="width: 155px" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="Search" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <!-- 列表区 -->
          <el-table ref="workshopTable" v-loading="loading" :data="workshopList" row-key="id" height="100%" :indent="20"
            default-expand-all highlight-current-row @current-change="handleGetDept">
            <el-table-column label="行号" type="index" width="50" align="center" />
            <el-table-column label="车间名称" prop="name" align="center" />
            <el-table-column label="操作" width="150" align="center">
              <template #default="scope">
                <el-button v-hasPermi="['business:workshop:edit']" link type="warning" icon="Edit"
                  @click="handleUpdateWorkshop(scope.row)">编辑</el-button>
                <el-button v-hasPermi="['business:workshop:remove']" link type="danger" icon="Delete"
                  @click="handleDeleteWorkshop(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>

    <!-- 右侧区域 -->
    <section class="list-part-container column-container" style="flex: 3">
      <!-- 工段 -->
      <section class="list-part-container column-container" style="flex: 1">
        <!-- 搜索区 -->
        <el-form class="list-search-container" :model="queryDeptParams" ref="queryRef" :inline="true">
          <el-form-item class="section-title" label="工段" />
          <el-form-item>
            <el-button v-hasPermi="['business:workshop:add']" type="primary" icon="Plus"
              :disabled="workshopList.length == 0" @click="handleAddDept">新增</el-button>
            <el-button v-hasPermi="['business:workshop:remove']" type="danger" icon="Delete" :disabled="ids.length == 0"
              @click="handleDeptDelete"> 删除</el-button>
          </el-form-item>
        </el-form>

        <!-- 列表区 -->
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table v-loading="deptLoading" :data="deptList" :row-key="getRowKey" height="100%"
              @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="工段名称" prop="deptName" align="center" />
              <el-table-column label="工段编码" prop="deptCode" align="center" />
            </el-table>
          </div>
        </div>
        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" v-model:page="queryDeptParams.pageNum"
          v-model:limit="queryDeptParams.pageSize" @pagination="getDeptList" />
      </section>
      <!-- 周转区 -->
      <section class="list-part-container column-container" style="flex: 1">
        <!-- 搜索区 -->
        <el-form class="list-search-container" :model="queryDeptParams" ref="queryRef" :inline="true">
          <el-form-item class="section-title" label="周转区" />
          <el-form-item>
            <el-button v-hasPermi="['business:workshop:add']" type="primary" icon="Plus"
              @click="handleShowTurnoverFormDialog(null)">新增</el-button>
          </el-form-item>
        </el-form>

        <!-- 列表区 -->
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table v-loading="turnoverLoading" :data="turnoverList" height="100%">
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="周转区名称" prop="code" width="160" align="center" />
              <el-table-column label="状态" width="80" prop="status" align="center">
                <template #default="scope">
                  <dict-tag :options="turnover_status" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" align="center" />
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button v-hasPermi="['business:workshop:edit']" link type="warning" icon="Edit"
                    @click="handleShowTurnoverFormDialog(scope.row.id)"> 编辑
                  </el-button>
                  <el-button v-hasPermi="['business:workshop:remove']" link type="danger" icon="Delete"
                    @click="handleDeleteTurnover(scope.row)"> 删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
    </section>

    <!-- 车间管理表单 -->
    <workshop-form ref="workshopRef" @handleSaveSuccess="getList" />
    <!-- 工段弹窗 -->
    <dept-form ref="deptChoiceRef" :multiple="true" :multiple-selected="handleDeptSelected" />
    <!-- 周转区弹窗 -->
    <turnover-form ref="turnoverRef" @handleSaveSuccess="handleRefreshTurnover" />
  </div>
</template>
<script setup>
import { listWorkshop, delWorkshop } from '@/api/business/workshop'
import { listDept, updateDeptWorkshop, updateDeptWorkshopByDeptId } from '@/api/system/dept'
import { listTurnover, delTurnover } from '@/api/business/workshopTurnover'
import deptForm from '@/views/business/workshop/DialogDept'
import turnoverForm from '@/views/business/workshop/DialogFormTurnover'
import workshopForm from './form'
const { proxy } = getCurrentInstance()
/** 字典数组区 */
const { turnover_status } = proxy.useDict('turnover_status')
/** 车间管理变量 */
const workshopList = ref([])
const loading = ref(false)
const currentWorkshop = ref({})
/** 工段变量 */
const deptList = ref([])
const deptLoading = ref(false)
const total = ref(0)
const ids = ref([])
/** 周转区 */
const turnoverList = ref([])
const turnoverLoading = ref(false)
/** 查询对象 */
const queryParams = ref({
  name: ''
})
const queryDeptParams = ref({
  pageSize: 10,
  pageNum: 1,
  deptCode: ''
})

/***********************  方法区  ****************************/
/***********************  车间管理事件  ****************************/
/** 查询车间管理列表 */
function getList() {
  loading.value = true
  currentWorkshop.value = {}
  listWorkshop(queryParams.value).then((res) => {
    if (res.code == 200) {
      workshopList.value = res.rows
      loading.value = false
      if (workshopList.value.length > 0) {
        currentWorkshop.value = workshopList.value[0]
        proxy.$refs.workshopTable.setCurrentRow(workshopList.value[0])
      } else {
        deptList.value = []
        total.value = 0
      }
    }
  })
}
/**车间查询 */
function handleSearch() {
  getList()
}
/** 车间新增按钮操作 */
function handleAdd() {
  proxy.$refs.workshopRef.open()
}

/** 修改按钮操作 */
function handleUpdateWorkshop(row) {
  proxy.$refs.workshopRef.open(row)
}

/**车间表点击事件 */
function handleGetDept(row) {
  if (row) {
    currentWorkshop.value = row
  }
  // 获取工段
  getDeptList()
  // 获取周转区
  getTurnovers()
}
/** 车间删除按钮操作 */
function handleDeleteWorkshop(row) {
  const _ids = row.id
  proxy.$modal
    .confirm('是否确认删除选中的车间？')
    .then(function () {
      return delWorkshop(_ids)
    })
    //删除车间的同时删除工段上workId
    .then(function () {
      return updateDeptWorkshopByDeptId({ workshopId: _ids })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => { })
}
/***********************  工段相关事件  ****************************/
//打开添加工段
const handleAddDept = () => {
  handleAddBatchDept()
}
/** 多选添加 */
function handleAddBatchDept() {
  let deptIds = []
  deptIds = deptList.value.map((item) => {
    return item.deptId
  })
  proxy.$refs.deptChoiceRef.open(deptIds)
}

// 工段多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => {
    return item.deptId
  })
}
/** 获取行 id */
function getRowKey(row) {
  return row.deptId
}

//工段多选带回
function handleDeptSelected(selection) {
  let deptInfo = {}
  let deptIds = []
  deptIds = selection.map((item) => {
    return item.deptId
  })
  deptInfo.workshopId = currentWorkshop.value.id
  deptInfo.ids = deptIds
  updateDeptWorkshop(deptInfo).then((res) => {
    if (res.code == 200) {
      handleGetDept(currentWorkshop.value)
      proxy.$modal.msgSuccess('添加成功！')
    }
  })
}
/**获得工段列表 */
function getDeptList() {
  deptLoading.value = true
  queryDeptParams.value.workshopId = currentWorkshop.value.id
  if (currentWorkshop.value.id) {
    listDept(queryDeptParams.value).then((res) => {
      if (res.code == 200) {
        deptList.value = res.rows
        total.value = res.total
      }
    })
  }
  deptLoading.value = false
}
/** 车间工段删除按钮操作 */
function handleDeptDelete() {
  proxy.$modal.confirm('是否确认删除选中的车间？').then(function () {
    updateDeptWorkshop({ ids: ids.value }).then((res) => {
      if (res.code == 200) {
        handleGetDept(currentWorkshop.value)
        proxy.$modal.msgSuccess('删除成功！')
      }
    })
  })
}

/********************************************** 周转区相关事件 **********************************************/
/** 刷新周转区事件 */
const handleRefreshTurnover = () => {
  getTurnovers()
}

//获得周转位置
const getTurnovers = () => {
  turnoverLoading.value = true
  listTurnover({ workshopId: currentWorkshop.value.id ?? '0' }).then((res) => {
    turnoverList.value = res.data
    turnoverLoading.value = false
  })
}

/** 打开周转区对话框事件 */
const handleShowTurnoverFormDialog = (id) => {
  proxy.$refs.turnoverRef.open({
    workshopId: currentWorkshop.value.id,
    id: id
  })
}

/** 删除周转区事件 */
function handleDeleteTurnover(row) {
  proxy.$modal
    .confirm('确定删除选中项？')
    .then(() => {
      return delTurnover(row.id)
    })
    .then(() => {
      getTurnovers()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => { })
}

onMounted(() => {
  getList()
})
</script>
