<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="请输入" v-model="queryParams.planningNumber" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="Search" @click="handleQuery"><i class="el-icon-thumb" aria-hidden="true" />搜索</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="subDetails"
            v-loading="loading"
            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="182" align="center" />
            <el-table-column label="图纸版本" prop="technologyVersion" width="108" align="center" />
            <el-table-column label="当前投产量" prop="productionVolume" width="80" align="center" />
            <el-table-column label="当前投产批数" prop="lotNumber" width="180" align="center" />
            <el-table-column label="下达日期" prop="issuanceDate" 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>
      <!-- 分页 -->
      <el-pagination class="pagination-container" background layout="prev, pager, next" :total="subDetailTotal"> </el-pagination>
    </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="loading"
            highlight-current-row
            height="100%"
            @current-change="handleProcessChange"
          >
            <el-table-column type="index" label="行号" width="50" 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()">批量设置操作者</el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table :data="equipmentList" v-loading="loading" 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" icon="setting" @click="handleSetUsers(scope.row)">设置操作者</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 { saveEquipmentUser } from '@/api/business/equipmentUser'
import { onMounted, ref } from 'vue'

/** 查询对象 */
const queryParams = ref({
  productDescription: ''
})
const loading = ref(false)
const subDetails = ref([])
const processList = ref([])
const equipmentList = ref([])
const singleUser = ref({})
const subDetailTotal = ref(0)
const currentSubDetail = 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 = () => {
  loading.value = true
  getProductionPlanDetailSubDetails(queryParams.value).then((res) => {
    subDetails.value = res.rows
    subDetailTotal.value = res.total
    loading.value = false
    if (subDetails.value.length > 0) {
      currentSubDetail.value = subDetails.value[0]
      proxy.$refs.subDetailsTable.setCurrentRow(currentSubDetail.value)
    }
  })
}

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

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

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

/**
 * 设备列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  multiple.value = selection.length > 1
  selections.value = selection
}
/**单选设备绑定操作人 */
function handleSingleSelected(row) {
  console.log(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({
          productionPlanDetailSubDetailEquipmentId: el.id,
          equipmentDetailId: el.equipmentDetailId,
          equipmentDetailCode: el.equipmentDetailCode,
          userId: em.userId,
          nickName: em.nickName
        })
      })
    })
  } else {
    /**
     * 单选设备绑定操作人
     */
    employees.forEach((em) => {
      equipmentUsers.push({
        productionPlanDetailSubDetailEquipmentId: singleUser.value.id,
        equipmentDetailId: singleUser.value.equipmentDetailId,
        equipmentDetailCode: singleUser.value.equipmentDetailCode,
        userId: em.userId,
        nickName: em.nickName
      })
    })
  }

  saveEquipmentUser(equipmentUsers).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功')
    }

    loadData()
  })
}

const handleSetUsers = (row) => {
  multiple.value = true
  if (row) {
    singleUser.value = row
  }

  proxy.$refs.personRef.open()
}

/************************************ 私有方法 ************************************/
const _getProcessDetailsByTechnicalProcessId = (technologicalProcessId) => {
  getProcessDetailsByTechnicalProcessId({ technologicalProcessId: technologicalProcessId }).then((res) => {
    processList.value = res.rows
    if (processList.value.length > 0) {
      currentProcess.value = processList.value[0]

      proxy.$refs.processTable.setCurrentRow(currentProcess.value)
    }
  })
}

const _getSubDetailProcessEquipments = (processId) => {
  getSubDetailProcessEquipments({
    productionPlanDetailSubDetailId: currentSubDetail.id,
    technologicalProcessId: currentSubDetail.technologicalProcessId,
    processId: processId
  }).then((res) => {
    equipmentList.value = res.rows
    if (res.rows.length === 0) {
      equipmentList.value = []
    }
  })
}
</script>
