<template>
  <div class="page-container column-container">
    <section class="list-part-container column-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-item label="产品描述：">
          <el-input placeholder="请输入产品描述" v-model="queryParams.keywords" clearable style="width: 200px" />
        </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">刷新</el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="planDetailTable" :data="detailPlanList" highlight-current-row height="100%" @current-change="handlePlanDetailCurrentChange">
            <el-table-column label="客户简称" prop="companyAlias" width="150" align="center" />
            <el-table-column label="生产计划单号" prop="productionPlanNo" width="110" align="center" />
            <el-table-column label="产品描述" prop="productDescription" align="center" />
            <el-table-column label="图纸版本" prop="technologyVersion" width="70" align="center" />
            <el-table-column label="投产量" prop="productionQuantity" width="80" align="center" />
            <el-table-column label="总批数" prop="totalLotNumber" width="80" align="center" />
            <el-table-column label="单批量" prop="oneLotQuantity" width="80" align="center" />
            <el-table-column label="尾批量" prop="lastLotQuantity" width="80" align="center" />
            <el-table-column label="批号状态" prop="lotCodeStatusCode" width="60" align="center" />
            <el-table-column label="累计投产" prop="materialPickUpQuantity" width="80" align="center" />
            <el-table-column label="库位" prop="storageLocation" width="80" align="center" />
            <el-table-column label="下达日期" prop="issueDate" width="120" align="center" />
            <el-table-column label="操作" width="70" align="center">
              <template #default="scope">
                <el-button link type="primary" @click="handleAddSubDetail(scope.row)">投产 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <!-- 分页 -->
    <el-pagination class="pagination-container" background layout="prev, pager, next" :total="total"> </el-pagination>
    <section class="list-part-container row-container" style="flex: 1">
      <section class="list-part-container" style="flex: 4">
        <!-- 下边页面开始 -->
        <!-- 搜索区 -->
        <el-form class="list-search-container" :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="subDetailsTable"
              :data="subList"
              highlight-current-row
              height="100%"
              @selection-change="handleSelectionChange"
              @current-change="handleSubDetailCurrentChange"
            >
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="生产计划单号" prop="productionPlanNo" width="110" align="center" />
              <el-table-column label="产品描述" prop="productDescription" align="center" />
              <el-table-column label="当前投产量" prop="productionVolume" width="80" align="center" />
              <el-table-column label="当前投产批数" prop="lotNumber" width="100" align="center">
                <template #default="scope">
                  <el-input-number
                    v-if="scope.row.editStatus"
                    v-model="scope.row.lotNumber"
                    placeholder="当前投产批数"
                    :controls="false"
                    :precision="0"
                    :min="0"
                    :max="scope.row.totalLotNumber"
                    align="center"
                  />
                  <span v-else>{{ scope.row.lotNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column label="下达日期" prop="issuanceDate" width="120" 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-column label="操作" width="150" align="center">
                <template #default="scope">
                  <el-button v-if="!scope.row.editStatus" icon="edit" link type="warning" @click="handleEditSubDetail(scope.row)">编辑 </el-button>
                  <el-button v-if="!scope.row.editStatus" icon="delete" link type="danger" @click="handleDelSubDetail(scope.row)">删除 </el-button>
                  <el-button v-if="scope.row.editStatus" icon="Check" link type="success" @click="handleSaveSubDetail(scope.row)">确认 </el-button>
                  <el-button v-if="scope.row.editStatus" icon="close" link type="info" @click="handleEditSubDetail(scope.row)">取消 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
      <section class="list-part-container" style="flex: 1">
        <!-- 中间开始 -->
        <el-form class="list-search-container" :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" highlight-current-row height="100%" @current-change="handleProcessCurrentChange">
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="工序" prop="processCode" align="center" />
              <!-- <el-table-column label="周转位置" prop="processCode" align="center" /> -->
            </el-table>
          </div>
        </div>
      </section>
      <section class="list-part-container" style="flex: 1">
        <el-form class="list-search-container" :inline="true">
          <el-form-item class="section-title" label="设置设备" />
          <el-form-item>
            <el-button icon="Plus" type="primary" :disabled="!processRow.id" @click="openEquipment">选择设备</el-button>
          </el-form-item>
        </el-form>
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table :data="equipmentList" highlight-current-row height="100%" @selection-change="handleEquipmentSelectionChange">
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="设备编码" prop="equipmentDetailCode" align="center">
                <template #default="scope">
                  <el-button link type="primary">{{ scope.row.equipmentDetailCode }} </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="60" align="center">
                <template #default="scope">
                  <el-button link type="danger" icon="delete" @click="handleEquipmentDelete(scope.row)">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
    </section>
    <!-- 表单 -->
    <production-batch-form ref="productionRef" :get-list="getList" />
    <equipment ref="equipmentRef" :get-list="getList" :multipleSelected="equipmentSelected" :multiple="true" />
  </div>
</template>

<script setup name="ProductionBatch">
import { ref } from 'vue'
import { listProductionPlanDetail } from '@/api/business/productionPlanDetail.js'
import { savePlanDetailSubDetail, listPlanDetailSubDetail, delPlanDetailSubDetail } from '@/api/business/planDetailSubDetail.js'
import { saveBatchEquipment, listEquipment, delEquipment } from '@/api/business/productionPlanDetailEquipment.js'
import { listProduct } from '@/api/business/product.js'
import { listTechnologicalProcessDetail } from '@/api/business/technologicalProcessDetail.js'
import equipment from '@/views/dialog/equipment.vue'
import productionBatchForm from './form'
const { proxy } = getCurrentInstance()

/** 生产子计划列表 */
const subList = ref([])
/** 工序列表 */
const processList = ref([])
/** 设备列表 */
const equipmentList = ref([])

const planDetailTable = ref(null)
const subDetailsTable = ref(null)
const processTable = ref(null)
/**生产计划批次点击对象 */
const detailRow = ref({})
/**子计划点击对象 */
const subRow = ref({})
const processRow = ref({})

const detailPlanList = ref([])
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

/**设备多选 */
const equipmentIds = ref([])
const equipmentSingle = ref(true)
const equipmentMultiple = ref(true)
const total = ref(2)
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  keywords: ''
})

/***********************  方法区  ****************************/

/** 查询生产批次列表 */
function getList() {
  loading.value = false
  listProductionPlanDetail(queryParams.value).then((res) => {
    detailPlanList.value = res.rows
    //生产子计划点击
    if (detailPlanList.value.length > 0) {
      proxy.$refs.planDetailTable.setCurrentRow(detailPlanList.value[0])
    }
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  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 handleEquipmentSelectionChange(selection) {
  equipmentIds.value = selection.map((item) => item.id)
  equipmentSingle.value = selection.length != 1
  equipmentMultiple.value = !selection.length
}

/** 生产计划明细 current-change 事件 */
function handlePlanDetailCurrentChange(row) {
  if (row) {
    detailRow.value = row
    listPlanDetailSubDetail({
      production_plan_detail_id: row.id
    }).then((res) => {
      subList.value = res.rows
      if (subList.value.length > 0) {
        proxy.$refs.subDetailsTable.setCurrentRow(subList.value[0])
      }
    })
  } else {
    subList.value = []
    processList.value = []
    equipmentList.value = []
  }
}
/** 生产子计划 current-change 事件 */
function handleSubDetailCurrentChange(row) {
  if (row) {
    subRow.value = row
    listTechnologicalProcessDetail({ technologicalProcessId: row.technologicalProcessId }).then((res) => {
      processList.value = res.rows
      if (processList.value.length > 0) {
        proxy.$refs.processTable.setCurrentRow(processList.value[0])
      }
    })
  } else {
    processList.value = []
    equipmentList.value = []
  }
}
/** 工序 current-change 事件 */
function handleProcessCurrentChange(row) {
  if (row) {
    processRow.value = row

    listEquipment({
      productionPlanDetailSubDetailId: subRow.value.id,
      technologicalProcessId: row.technologicalProcessId,
      processId: row.id
    }).then((res) => {
      if (res.code == 200) {
        equipmentList.value = res.rows
      }
    })
  } else {
    equipmentList.value = []
  }
}

/** 设备选择对话框 */
function openEquipment() {
  proxy.$refs.equipmentRef.open()
}

/**新增按钮生产子计划 */
function handleAddSubDetail(row) {
  /**创建一个空的对象，将生产计划中的数据赋值给子计划数据 */
  const newDetail = {}
  newDetail.productionPlanId = row.productionPlanId
  newDetail.productionPlanDetailId = row.id
  newDetail.lotNumber = row.totalLotNumber
  newDetail.productionPlanNo = row.productionPlanNo
  newDetail.productionQuantity = row.productionQuantity
  newDetail.productId = row.productId
  newDetail.productDescription = row.productDescription
  //给下达日期一个当前日期的默认值
  const date = new Date()
  newDetail.issuanceDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
  // 打开 生产子计划 对话框
  handleEditSubDetail(newDetail)
}

/** 修改 生产子计划 事件 */
function handleEditSubDetail(row) {
  proxy.$refs.productionRef.open(row)
}

/** 生产子计划 保存事件 */
function handleSaveSubDetail(row) {
  savePlanDetailSubDetail(row).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('保存成功！')
      handlePlanDetailCurrentChange(detailRow.value)
    }
  })
}

/** 删除子计划事件 */
function handleDelSubDetail(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delPlanDetailSubDetail(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => {})
}

/** 删除设备事件 */
function handleEquipmentDelete(row) {
  const _ids = row.id || equipmentIds.value
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delEquipment(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功！')
    })
    .catch(() => {})
}
function equipmentSelected(selection) {
  const equipment = []
  for (let i = 0; i < selection.length; i++) {
    const item = {}
    item.productionPlanId = detailRow.value.productionPlanId
    item.productionPlanDetailId = detailRow.value.id
    item.productionPlanDetailSubDetailId = subRow.value.id
    item.productId = subRow.value.productId
    item.technologicalProcessId = subRow.value.technologicalProcessId
    item.processId = processRow.value.id
    item.equipmentDetailId = selection[i].id
    item.equipmentDetailCode = selection[i].usageDeptCode
    equipment.push(item)
  }
  saveBatchEquipment(equipment).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('保存成功！')
      handleProcessCurrentChange(processRow.value)
    }
  })
}

/** */

onMounted(() => {
  getList()
})
</script>
<style scoped>
.list-search-container-child .el-form-item {
  /* 修改样式 */
  margin-right: 10px;
}
</style>
