<template>
  <div class="page-container row-container">
    <section class="list-part-container" style="flex: 4">
      <!-- 下边页面开始 -->
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="生产子计划" />
        <el-form-item label="产品描述：">
          <el-input placeholder="请输入" style="width: 180px" @keyup.enter="handleQuery" @keydown.enter.prevent clearable v-model.trim="queryParams.productDescription" />
        </el-form-item>
        <!-- <el-form-item class="section-title" label="当前工段：">
          <el-select-v2 v-model="queryParams.deptId" filterable :options="deptList" placeholder="请选择工段" @change="handleDeptChange" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="info" icon="Search" @click="handleQuery">搜索</el-button>
          <!-- <el-button type="primary" icon="Refresh" @click="handleQuery">刷新</el-button> -->
        </el-form-item>

      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="subDetailsTable" :data="subDetailsList" v-loading="subDetailsLoading" highlight-current-row height="100%" @current-change="handleSubDetailChange">
            <el-table-column type="index" label="行号" width="50px" align="center" />
            <el-table-column label="生产计划单号" prop="productionPlanNo" width="110" align="center" />
            <el-table-column label="产品描述" prop="productDescription" width="auto" align="center" />
            <el-table-column label="图纸版本" prop="technologyVersion" width="108" align="center" />
            <el-table-column label="首序投产量" prop="productionQuantity" width="80" align="center" />
            <el-table-column label="首序投产批数" prop="lotNumber" width="180" align="center" />
            <el-table-column label="下达日期" prop="issuanceDate" width="100px" align="center">
              <template #default="scope">
                <el-date-picker v-if="scope.row.editStatus" clearable v-model="scope.row.issuanceDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择实际开始 时间" />
                <span v-else>{{ scope.row.issuanceDate }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 分页 -->
      <pagination v-show="subDetailTotal > 0" :total="subDetailTotal" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="loadData" />
    </section>
    <section class="list-part-container" style="flex: 1">
      <!-- 中间开始 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="工序" />
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="processTable" :data="processList" v-loading="processLoading" highlight-current-row height="100%" @current-change="handleProcessChange">
            <el-table-column type="index" label="行号" width="50" align="center" />
            <el-table-column label="工序名称" prop="processAlias" align="center" />
            <el-table-column label="工序编码" prop="processCode" align="center" />
          </el-table>
        </div>
      </div>
    </section>
    <section class="list-part-container" style="flex: 2">
      <el-form class="list-search-container list-search-container-child" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="设备列表" />
        <el-form-item>
          <el-button type="primary" icon="Finished" :disabled="selections.length === 0" @click="handleSetUsers()" v-hasPermi="['business:productionTask:add']">批量设置操作者</el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table :data="equipmentList" v-loading="equipmentLoading" highlight-current-row 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="equipmentDetailCode" width="60" align="center" />
            <el-table-column label="操作者" prop="userNickNames" align="center" />
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button link type="primary" :disabled="selections.length > 0" icon="setting" @click="handleSetUsers(scope.row)" v-hasPermi="['business:productionTask:add']">设置操作者</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>

    <person ref="personRef" :multiple="multiple" :multiple-selected="handleMultipleSelected" :single-selected="handleSingleSelected" />
  </div>
</template>
<script setup name="ProductionTask">
import person from '@/views/dialog/person.vue'
import { getProductionPlanDetailSubDetails, getProcessDetailsByTechnicalProcessId, getSubDetailProcessEquipments } from '@/api/business/productionTask'
import { getDept } from '@/api/business/planDetailSubDetail.js'
import { saveEquipmentUser } from '@/api/business/equipmentUser'
import { onMounted, ref } from 'vue'

/** 查询对象 */
const queryParams = ref({
  productDescription: '',
  pageNum: 1,
  pageSize: 10
})
const subDetailsLoading = ref(false)
const processLoading = ref(false)
const equipmentLoading = ref(false)
const subDetailsList = ref([])
const processList = ref([])
const equipmentList = ref([])
const processRow = ref({})
const singleUser = ref({})
const subDetailTotal = ref(0)
const currentSubDetail = ref({})
/**当前工段列表 */
const deptList = ref([])
const currentProcess = ref({})
const currentEquipment = ref({})
const selections = ref([])
const multiple = ref(false)
const personRef = ref(null)
const subDetailsTable = ref(null)
const processTable = ref(null)
const { proxy } = getCurrentInstance()

onMounted(() => {
  loadData()
})

// 加载 生产子计划数据
const loadData = () => {
  // getDept().then((response) => {
  //   deptList.value = response.data
  //   if (deptList.value.length >0) {
  //     queryParams.value.deptId = deptList.value[0].value

  //   }
  // })
  getSubDetail()
}

/**查询子计划列表 */
function getSubDetail() {
  subDetailsLoading.value = true
  getProductionPlanDetailSubDetails(queryParams.value).then((res) => {
    subDetailsList.value = res.rows
    subDetailTotal.value = res.total
    subDetailsLoading.value = false
    if (subDetailsList.value.length > 0) {
      proxy.$refs.subDetailsTable.setCurrentRow(subDetailsList.value[0])
    } else {
      processList.value = []
      equipmentList.value = []
    }
  })
}

// 搜索事件
const handleQuery = () => {
  getSubDetail()
}

// 子计划的change事件
const handleSubDetailChange = (row) => {
  if (row) {
    currentSubDetail.value = row
    _getProcessDetailsByTechnicalProcessId(row.technologicalProcessId)
  }
}

// 工序的change事件
const handleProcessChange = (row) => {
  if (row) {
    processRow.value = row
    _getSubDetailProcessEquipments(row.processId)
  }
}

/**
 * 设备列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  multiple.value = selection.length > 1
  selections.value = selection
}
/**单选设备绑定操作人 */
function handleSingleSelected(row) {
  currentEquipment.value = row
}
// 多选操作者后的回调事件
const handleMultipleSelected = (employees) => {
  const equipmentUsers = []
  /**
   * 这里有个细节，批量勾选设备，再多选多个员工
   * 需要双双循环，形成一个数组，再将数据保存到
   * production_plan_detail_sub_detail_equipment_user 表中
   */
  if (selections.value.length > 0) {
    selections.value.forEach((el) => {
      employees.forEach((em) => {
        equipmentUsers.push({
          productionPlanDetailSubDetailId: currentSubDetail.value.id,
          processId: processRow.value.processId,
          product: processRow.value.productId,
          productionPlanDetailId: currentSubDetail.value.productionPlanDetailId,
          technologicalProcessId: currentSubDetail.value.technologicalProcessId,
          productionPlanDetailSubDetailEquipmentId: el.id,
          equipmentDetailId: el.equipmentDetailId,
          equipmentDetailCode: el.equipmentDetailCode,
          userId: em.userId,
          nickName: em.nickName
        })
      })
    })
  } else {
    /**
     * 单选设备绑定操作人
     */
    employees.forEach((em) => {
      equipmentUsers.push({
        productionPlanDetailSubDetailId: currentSubDetail.value.id,
        productionPlanDetailId: currentSubDetail.value.productionPlanDetailId,
        technologicalProcessId: currentSubDetail.value.technologicalProcessId,
        processId: processRow.value.processId,
        product: processRow.value.productId,
        productionPlanDetailSubDetailEquipmentId: singleUser.value.id,
        equipmentDetailId: singleUser.value.equipmentDetailId,
        equipmentDetailCode: singleUser.value.equipmentDetailCode,
        userId: em.userId,
        nickName: em.nickName,
        processId: processRow.value.processId
      })
    })
  }
  saveEquipmentUser(equipmentUsers).then((res) => {
    if (res.code == 200) {
      _getSubDetailProcessEquipments(processRow.value.processId)
      proxy.$modal.msgSuccess('操作成功')
    }
  })
}
/**工段下拉框change事件 */
function handleDeptChange() {
  getSubDetail()
}
const handleSetUsers = (row) => {
  multiple.value = true
  if (row) {
    singleUser.value = row
  }
  const userInfo = {}
  userInfo.identifying = false
  userInfo.deptId = queryParams.value.deptId
  proxy.$refs.personRef.open(userInfo)
}

/************************************ 私有方法 ************************************/
const _getProcessDetailsByTechnicalProcessId = (technologicalProcessId) => {
  processLoading.value = true
  getProcessDetailsByTechnicalProcessId({ technologicalProcessId: technologicalProcessId }).then((res) => {
    processList.value = res.rows
    processLoading.value = false
    if (processList.value.length > 0) {
      proxy.$refs.processTable.setCurrentRow(processList.value[0])
    }
  })
}

const _getSubDetailProcessEquipments = (processId) => {
  equipmentLoading.value = true
  getSubDetailProcessEquipments({
    productionPlanDetailSubDetailId: currentSubDetail.value.id,
    technologicalProcessId: currentSubDetail.value.technologicalProcessId,
    processId: processId
  }).then((res) => {
    equipmentList.value = res.rows
    equipmentLoading.value = false
  })
}
</script>
