<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-select v-model="queryParams.type" clearable placeholder="请选择类别">
            <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户集团简称：">
          <el-input placeholder="请输入客户集团简称" v-model.trim="queryParams.companyAlias" style="width: 150px" />
        </el-form-item>
        <el-form-item label="产品图号：">
          <el-input placeholder="请输入产品图号" v-model.trim="queryParams.drawingNumber" style="width: 150px" />
        </el-form-item>
        <el-form-item label="产品规格：">
          <el-input placeholder="请输入产品规格" v-model.trim="queryParams.specification" style="width: 150px" />
        </el-form-item>
        <el-form-item>
          <el-button type="info" icon="Search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <div class="list-btns-container">
        <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:product:add']">新增</el-button>
      </div>
      <!-- 列表区 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table
            ref="productTable"
            v-loading="productLoading"
            :data="productList"
            row-key="id"
            highlight-current-row
            height="100%"
            @selection-change="handleSelectionChange"
            @current-change="getTechnologicalProcess"
          >
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column label="料号" align="center" prop="productCode" />
            <el-table-column label="预入仓库" align="center" prop="preStock" />
            <el-table-column label="类别" align="center" prop="type">
              <template #default="scope">
                <dict-tag :options="product_type" :value="scope.row.type" />
              </template>
            </el-table-column>
            <el-table-column label="轴类型大类" width="150px" align="center" prop="shaftBroadCategoryCode">
              <template #default="scope">
                <dict-tag :options="product_dtype" :value="scope.row.shaftBroadCategoryCode" />
              </template>
            </el-table-column>
            <el-table-column label="轴类型" align="center" prop="shaftCategoryCode" />
            <el-table-column label="规格" align="center" prop="specification" />
            <el-table-column label="图号" align="center" prop="drawingNumber" />
            <el-table-column label="客户集团简称" align="center" width="120px" prop="companyAlias" />
            <el-table-column label="客户简称_图号_规格" align="center" width="140px" prop="description" />
            <el-table-column label="直径" align="center" prop="diameter" />
            <el-table-column label="成品长度" align="center" prop="lenght" />
            <el-table-column label="厚度" align="center" prop="thickness" />
            <el-table-column label="客户代号" align="center" prop="companyCode" />
            <el-table-column label="销售员编码" align="center" prop="salesmanCode" />
            <el-table-column label="保管员编码" align="center" prop="stockKeeperCode" />
            <el-table-column label="调度员编号" align="center" prop="dispatcherCode" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="产品状态" align="center" prop="productStatusCode">
              <template #default="scope">
                <dict-tag :options="product_status_code" :value="scope.row.productStatusCode" />
              </template>
            </el-table-column>
            <el-table-column label="生产类型" align="center" prop="productionTypeCode">
              <template #default="scope">
                <dict-tag :options="production_type_code" :value="scope.row.productionTypeCode" />
              </template>
            </el-table-column>
            <el-table-column label="技术员编码" align="center" prop="technicianCode" />
            <el-table-column label="操作" align="center" width="140px">
              <template #default="scope">
                <el-button link type="warning" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:product:edit']">编辑</el-button>
                <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:product:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <!-- 分页 -->
    <el-pagination class="pagination-container" background layout="prev, pager, next" :total="total" @pagination="getList"> </el-pagination>
    <section class="list-part-container row-container" style="flex: 1">
      <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-item>
            <el-button type="primary" icon="Plus" @click="handleAddTechnologicalProcess" v-hasPermi="['business:product:add']">添加工艺</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="TechnologicalProcessDelete"
              :disabled="technologicalProcessMultiple"
              v-hasPermi="['system:product:remove']"
              >删除工艺</el-button
            >
          </el-form-item>
        </el-form>
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table
              ref="technologicalProcessTable"
              :data="technologicalProcessList ? technologicalProcessList : []"
              v-loading="technologicalProcessLoading"
              :row-key="getRowKey"
              highlight-current-row
              height="100%"
              size="small"
              header-row-class-name="list-header-row"
              @selection-change="TechnologicalProcessSelectionChange"
              @current-change="getTechnologicalProcessDetail"
            >
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="工艺版本" align="center" prop="technologyVersion">
                <template #default="scope">
                  <div v-if="scope.row.editStatus">
                    <el-input v-model.trim="scope.row.technologyVersion" size="small" placeholder="工艺版本" />
                  </div>
                  <div v-else>{{ scope.row.technologyVersion }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="140px" align="center">
                <template #default="scope">
                  <el-button
                    v-if="scope.row.editStatus"
                    link
                    type="primary"
                    icon="Check"
                    @click="handleUpdateTechnologicalProcess(scope.row, scope.$index)"
                    v-hasPermi="['business:craft:add']"
                    >保存</el-button
                  >

                  <el-button v-else link type="warning" icon="Edit" @click.prevent="scope.row.editStatus = true" v-hasPermi="['business:craft:edit']"
                    >编辑</el-button
                  >
                  <el-button
                    link
                    type="danger"
                    icon="Delete"
                    @click="handleDeleteTechnologicalProcess(scope.row, scope.$index)"
                    v-hasPermi="['business:craft:remove']"
                    >删除</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 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="Plus"
              @click="handleAddProcess"
              :disabled="technologicalProcessAddMultiple"
              v-hasPermi="['business:process:add']"
              >添加工序</el-button
            >
            <el-button
              type="danger"
              icon="Delete"
              @click="handledelTechnologicalProcessDetail"
              :disabled="technologicalProcessDetailMultiple"
              v-hasPermi="['business:process:remove']"
              >删除工序</el-button
            >
          </el-form-item>
        </el-form>
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table
              :data="technologicalprocessDetailList"
              v-loading="technologicalprocessDetailLoading"
              highlight-current-row
              height="100%"
              @row-click="processDetailSelectionChange"
            >
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="工序步骤编号" align="center" prop="processStepNumber" />
              <el-table-column label="工序编码" align="center" prop="processCode" />
              <el-table-column label="工序简称" align="center" prop="processAlias" />
              <el-table-column label="图纸" prop="drawingFile" align="center" />
            </el-table>
          </div>
        </div>
      </section>
    </section>
    <!-- 表单 -->
    <product-form ref="productRef" :get-list="getList"></product-form>
    <process-choice
      ref="processChoiceRef"
      :get-list="getList"
      :multiple="true"
      :multiple-selected="handleProcessSelected"
      :selected="processList"
    ></process-choice>
  </div>
</template>

<script setup name="Product">
import { listProduct, delProduct } from '@/api/business/product'
import productForm from './form'
import processChoice from './DialogProcessChoice.vue'
import {
  listTechnologicalProcessDetail,
  addTechnologicalProcessDetail,
  delTechnologicalProcessDetail
} from '@/api/business/technologicalProcessDetail'
import {
  listTechnologicalProcess,
  addTechnologicalProcess,
  updateTechnologicalProcess,
  delTechnologicalProcess
} from '@/api/business/technologicalProcess'
import { ref } from 'vue'
const { proxy } = getCurrentInstance()
/** 字典数组区 */
const { product_type } = proxy.useDict('product_type')
const { product_dtype } = proxy.useDict('product_dtype')
const { product_status_code } = proxy.useDict('product_status_code')
const { production_type_code } = proxy.useDict('production_type_code')

/** 查询 对象 */
const productList = ref([])
const technologicalProcessList = ref([])
const processList = ref([])
const technologicalprocessDetailList = ref([])
const productLoading = ref(false)
const technologicalProcessLoading = ref(false)
const technologicalprocessDetailLoading = ref(false)
const ids = ref([])
const technologicalProcessIds = ref([])
const technologicalProcessDetailIds = ref([])
const single = ref(true)
const multiple = ref(true)
const technologicalProcessMultiple = ref(true)
const technologicalProcessDetailMultiple = ref(true)
const technologicalProcessAddMultiple = ref(true)
const total = ref(0)
const detailsRow = {
  id: null,
  tenantId: null,
  technologyVersion: undefined,
  productCode: undefined,
  productShaftCategory: undefined,
  productShaftCategoryName: undefined,
  productDescription: undefined
}
const technologicalProcessDetail = ref({})
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  code: null,
  name: null,
  combinedValue: null
})

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

/** 查询产品管理列表
 * 进入页面产品表第一条和工艺表第一条默认选中
 */
function getList() {
  productLoading.value = true
  listProduct(queryParams.value).then((response) => {
    productList.value = response.rows
    total.value = response.total
    productLoading.value = false
    proxy.$refs.productTable.setCurrentRow(productList.value[0])
    if (productList.value.length > 0) {
      getTechnologicalProcess(productList.value[0])
    } else {
      technologicalProcessList.value = []
      technologicalprocessDetailList.value = []
    }
  })
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
//工序多选框选中数据
function processDetailSelectionChange(selection) {
  technologicalProcessDetailIds.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  technologicalProcessDetailMultiple.value = !selection.length
}
/** 获取行 id */
function getRowKey(row) {
  return row.id
}
/** 工序表多选带回保存
 * 将弹出框选中的内容保存到工序表
 */
function handleProcessSelected(selection) {
  console.log('多选带回', selection)
  for (var i = 0; i < selection.length; i++) {
    var technologicalProcessDetailAdd = {}
    technologicalProcessDetailAdd.tenantId = technologicalProcessDetail.value.tenantId
    technologicalProcessDetailAdd.technologicalProcessId = technologicalProcessDetail.value.technologicalProcessId
    technologicalProcessDetailAdd.productId = technologicalProcessDetail.value.productId
    technologicalProcessDetailAdd.productCode = technologicalProcessDetail.value.productCode
    technologicalProcessDetailAdd.processId = selection[i].id
    technologicalProcessDetailAdd.processAlias = selection[i].processAlias
    technologicalProcessDetailAdd.processCode = selection[i].processCode
    technologicalProcessDetailAdd.productShaftCategory = technologicalProcessDetail.value.productShaftCategory
    technologicalProcessDetailAdd.productShaftCategoryName = technologicalProcessDetail.value.productShaftCategoryName
    technologicalProcessDetailAdd.productDescription = technologicalProcessDetail.value.productDescription
    technologicalprocessDetailList.value.push(technologicalProcessDetailAdd)
  }
  addTechnologicalProcessDetail(technologicalprocessDetailList.value).then((response) => {
    console.log(response)
    if (response.code === 200) {
      proxy.$modal.msgSuccess('添加成功！')
    }
  })
}
/** 工艺表多选框选中数据 */
function TechnologicalProcessSelectionChange(selection) {
  technologicalProcessIds.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  technologicalProcessMultiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$refs.productRef.open()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const id = row.id || ids.value
  proxy.$refs.productRef.open(id)
}
/** 修改工艺操作：通过id绑定，重新将工艺版本赋值
 * 添加工艺操作：添加后，执行刷新操作，重新查找工艺表内容，并通过绑定添加行的下标来选中，从而获得row
 */
function handleUpdateTechnologicalProcess(row, index) {
  for (var i = 0; i < technologicalProcessList.value.length; i++) {
    if (row.id == technologicalProcessList.value[i].id) {
      technologicalProcessList.value[i].technologicalVersion = row.technologicalVersion
    }
  }
  addTechnologicalProcess(technologicalProcessList.value).then((response) => {
    if (response.code == 200) {
      listTechnologicalProcess({ productId: row.productId }).then((res1) => {
        technologicalProcessList.value = res1.rows
        proxy.$refs.technologicalProcessTable.setCurrentRow(technologicalProcessList.value[index])
      })
      console.log(row)
      proxy.$modal.msgSuccess('操作成功！')
    }
  })

  row.editStatus = false
}

/** 查询工艺列表
 * 点击产品表，通过产品id查询工艺表
 */
function getTechnologicalProcess(row) {
  technologicalProcessDetail.value = row
  technologicalProcessLoading.value = true
  listTechnologicalProcess({ productId: row.id }).then((response) => {
    technologicalProcessList.value = response.rows
    technologicalProcessLoading.value = false
    proxy.$refs.technologicalProcessTable.setCurrentRow(technologicalProcessList.value[0])
    if (technologicalProcessList.value.length > 0) {
      getTechnologicalProcessDetail(technologicalProcessList.value[0])
    } else {
      technologicalProcessList.value = []
      technologicalprocessDetailList.value = []
    }
  })
}
/** 查询工序列表
 * 通过工艺id来查询工序表
 */
function getTechnologicalProcessDetail(row) {
  technologicalProcessAddMultiple.value = true
  console.log(row, 'row')
  technologicalprocessDetailLoading.value = true
  technologicalProcessDetail.value.technologicalProcessId = row.id
  if (row.id) {
    technologicalProcessAddMultiple.value = false
    listTechnologicalProcessDetail({ technologicalProcessId: row.id }).then((response) => {
      if (response.code == 200) {
        technologicalprocessDetailList.value = response.rows
      }
    })
  } else {
    technologicalprocessDetailList.value = []
  }
  technologicalprocessDetailLoading.value = false
}
/** 红叉按钮刷新或取消 */
function handleCancel(row) {
  if (row.id) {
    row.editStatus = false
  } else {
    listTechnologicalProcess({ productId: row.productId }).then((response) => {
      if (response.code == 200) {
        technologicalProcessList.value = response.rows
        proxy.$modal.msgSuccess('操作成功！')
      }
    })
  }
}

/** 删除产品表操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  console.log(_ids)
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      delProduct(_ids).then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功！')
      })
    })
    .catch(() => {})
}

/** 单条删除工艺操作
 * 删除已经存在的数据-即row.id存在，执行一个对话框选择，如果确认则执行删除方法，并重新查询工艺表操作，
 * 让工艺表第一条默认选中
 * 删除未保存的苏剧-即row.id不存在，通过splice方法，通过下标删除数组的元素
 */
function handleDeleteTechnologicalProcess(row, index) {
  if (row.id) {
    proxy.$modal
      .confirm('是否确认删除选中的数据项？')
      .then(function () {
        return delTechnologicalProcess(row.id)
      })
      .then(() => {
        listTechnologicalProcess({ productId: row.productId }).then((response) => {
          if (response.code == 200) {
            technologicalProcessList.value = response.rows
            if (technologicalProcessList.value.length > 0) {
              proxy.$refs.technologicalProcessTable.setCurrentRow(technologicalProcessList.value[0])
            } else {
              technologicalProcessList.value = []
              processList.value = []
            }
            proxy.$modal.msgSuccess('删除成功！')
          }
        })
      })
      .catch((e) => {
        console.log(e)
        proxy.$modal.msg('操作失败！')
      })
  } else {
    technologicalProcessList.value.splice(index, 1)
  }
}

/** 工艺表批量删除操作
 * 通过多选框选中方法，获得选中的工艺id，执行删除，山删除后，重新通过产品id获得工艺列表
 */
function TechnologicalProcessDelete() {
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delTechnologicalProcess(technologicalProcessIds.value)
    })
    .then(() => {
      listTechnologicalProcess({ productId: technologicalProcessDetail.value.productId }).then((response) => {
        if (response.code == 200) {
          technologicalProcessList.value = response.rows
          if (technologicalProcessList.value.length > 0) {
          } else {
            technologicalProcessList.value = []
            processList.value = []
          }
          proxy.$modal.msgSuccess('删除成功！')
        }
      })
    })
    .catch((e) => {
      console.log(e)
      proxy.$modal.msg('操作失败！')
    })
}
/** 工序表批量删除操作
 * 通过多选框获得选中的工序id，执行删除操作后执行查询操作
 */
function handledelTechnologicalProcessDetail() {
  proxy.$modal
    .confirm('是否确认删除选中的数据项？')
    .then(function () {
      return delTechnologicalProcessDetail(technologicalProcessDetailIds.value)
    })
    .then(() => {
      listTechnologicalProcessDetail({ productId: technologicalProcessDetail.value.productId }).then((response) => {
        if (response.code == 200) {
          technologicalprocessDetailList.value = response.rows
          proxy.$modal.msgSuccess('删除成功！')
        }
      })
    })
    .catch((e) => {
      console.log(e)
      proxy.$modal.msg('操作失败！')
    })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'business/product/export',
    {
      ...queryParams.value
    },
    `product_${new Date().getTime()}.xlsx`
  )
}
/** 添加工序 */
function handleAddProcess() {
  proxy.$refs.processChoiceRef.open()
}
/** 工艺添加操作 */
const handleAddTechnologicalProcess = () => {
  const newDetail = JSON.parse(JSON.stringify(detailsRow))
  newDetail.editStatus = true
  newDetail.productCode = technologicalProcessDetail.value.productCode
  newDetail.productId = technologicalProcessDetail.value.productId
  newDetail.productShaftCategoryId = technologicalProcessDetail.value.productShaftCategoryId
  newDetail.productDrawingNumber = technologicalProcessDetail.value.productDrawingNumber
  newDetail.productDescription = technologicalProcessDetail.value.productDescription
  newDetail.productSpecification = technologicalProcessDetail.value.productSpecification
  newDetail.tenantId = technologicalProcessDetail.value.tenantId
  technologicalProcessList.value.push(newDetail)
}
/** 工艺添加取消操作 */

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