<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width='120'>
            <el-form-item label="工装类型编号" prop="toolingTypeCode">
              <el-input v-model="queryParams.toolingTypeCode" placeholder="请输入工装类型编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="工装类型名称" prop="toolingTypeName">
              <el-input v-model="queryParams.toolingTypeName" placeholder="请输入工装类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mes:toolingType:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['mes:toolingType:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['mes:toolingType:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['mes:toolingType:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="toolingTypeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键标识" align="center" prop="toolingTypeId" v-if="columns[0].visible"/>
        <el-table-column label="工装类型编号" align="center" prop="toolingTypeCode" v-if="columns[2].visible"/>
        <el-table-column label="工装类型名称" align="center" prop="toolingTypeName" v-if="columns[3].visible"/>
        <el-table-column label="工装类型规格" align="center" prop="toolingSpecCode" v-if="columns[4].visible"/>
        <el-table-column label="标准使用次数/秒" align="center" prop="standardLife" v-if="columns[5].visible"/>
        <el-table-column label="标准重量(kg)" align="center" prop="standardWeight" v-if="columns[6].visible"/>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[7].visible"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button size="small" type="text" icon="el-icon-edit" @click="handleRelationMaterial(scope.row)">关联物料</el-button>
            <el-button size="small" type="text" icon="el-icon-edit" @click="handleRelationProcess(scope.row)">关联工序</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改载具工装类型对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="toolingTypeFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="工装类型编号" prop="toolingTypeCode">
          <el-input v-model="form.toolingTypeCode" placeholder="请输入工装类型编号" />
        </el-form-item>
        <el-form-item label="工装类型名称" prop="toolingTypeName">
          <el-input v-model="form.toolingTypeName" placeholder="请输入工装类型名称" />
        </el-form-item>
        <el-form-item label="工装类型规格" prop="toolingSpecCode">
          <el-input v-model="form.toolingSpecCode" placeholder="请输入工装类型规格" />
        </el-form-item>
        <el-form-item label="标准使用次数/秒" prop="standardLife">
          <el-input-number v-model="form.standardLife" placeholder="请输入标准使用次数/秒" />
        </el-form-item>
        <el-form-item label="标准重量(kg)" prop="standardWeight">
          <el-input-number v-model="form.standardWeight" placeholder="请输入标准重量(kg)" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="'维护工装类型关联物料'" v-model="materialDialogOpen" width="700px" append-to-body>
      <el-form label-width="120px" class="mb8">
        <el-form-item label="工装类型编号">
          <el-input v-model="currentToolingTypeCode" readonly />
        </el-form-item>
        <el-form-item label="工装类型名称">
          <el-input v-model="currentToolingTypeName" readonly />
        </el-form-item>
      </el-form>
      <el-divider content-position="center">工装类型关联物料信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" size="small" @click="handleAddRelationMaterial">添加物料</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="Delete" size="small" @click="handleDeleteRelationMaterial">删除</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="form.typeRelationList"
        :row-class-name="rowRelationMaterialIndex"
        @selection-change="handleRelationMaterialSelectionChange"
        ref="relationMaterialTableRef"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="关联物料" prop="relationInfoId" align="center">
          <template #default="scope">
            <el-input
              v-model="scope.row.materialName"
              :placeholder="scope.row.materialName ? '': '请点击选择物料'"
              readonly
              @click="openMaterialDialog(scope.$index)"
            />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
          <el-button @click="materialDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="选择物料信息" v-model="materialSelectDialogOpen" width="1200px" append-to-body>
      <MaterialSelect ref="materialSelectRef" v-if="materialSelectDialogOpen"></MaterialSelect>
      <template #footer>
        <el-button type="primary" @click="handleMaterialSelection">确 定</el-button>
        <el-button @click="materialSelectDialogOpen = false">取 消</el-button>
      </template>
    </el-dialog>
    <el-dialog :title="'维护工装类型关联工序'" v-model="processDialogOpen" width="700px" append-to-body>
      <el-form label-width="120px" class="mb8">
        <el-form-item label="工装类型编号">
          <el-input v-model="currentToolingTypeCode" readonly />
        </el-form-item>
        <el-form-item label="工装类型名称">
          <el-input v-model="currentToolingTypeName" readonly />
        </el-form-item>
      </el-form>
      <el-divider content-position="center">工装类型关联工序信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" size="small" @click="handleAddRelationProcess">添加工序</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="Delete" size="small" @click="handleDeleteRelationProcess">删除</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="form.processList"
        :row-class-name="rowRelationProcessIndex"
        @selection-change="handleRelationProcessSelectionChange"
        ref="relationProcessTableRef"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="关联工序" prop="relationInfoId" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.relationInfoId"
              placeholder="请选择工序名称"
              @change="handleProcessChange(scope.$index)"
            >
              <el-option
                v-for="item in processInfoList"
                :key="item.processId"
                :label="item.processName"
                :value="item.processId"
                :disabled="form.processList.some((row, idx) => row.relationInfoId === item.processId && idx !== scope.$index)"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitProcessForm">确 定</el-button>
          <el-button @click="processDialogOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="ToolingType" lang="ts">
import { listToolingType, getToolingType, delToolingType, addToolingType, updateToolingType } from '@/api/mes/toolingType';
import { ToolingTypeVO, ToolingTypeQuery, ToolingTypeForm } from '@/api/mes/toolingType/types';
import MaterialSelect from '@/views/mes/baseMaterialInfo/addMaterial.vue';
import { getProcessInfoList } from '@/api/mes/baseProcessInfo';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const toolingTypeList = ref<ToolingTypeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const toolingTypeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const materialDialogOpen = ref(false);
const materialSelectDialogOpen = ref(false);
const materialSelectRef = ref();
const relationMaterialTableRef = ref();
let currentToolingTypeId = ref<string | number | undefined>(undefined);
let currentToolingTypeCode = ref<string>('');
let currentToolingTypeName = ref<string>('');
const checkedRelationMaterial = ref<any[]>([]);
const currentMaterialRowIndex = ref(-1);

const processDialogOpen = ref(false);
const relationProcessTableRef = ref();
const checkedRelationProcess = ref<any[]>([]);

// 列显隐信息
const columns = ref<FieldOption[]>([
        { key: 0, label: `主键标识`, visible: false },
        { key: 1, label: `租户编号`, visible: false },
        { key: 2, label: `工装类型编号`, visible: true },
        { key: 3, label: `工装类型名称`, visible: true },
        { key: 4, label: `工装类型规格`, visible: true },
        { key: 5, label: `标准使用次数/秒`, visible: true },
        { key: 6, label: `标准重量(kg)`, visible: true },
        { key: 7, label: `备注`, visible: false },
        { key: 8, label: `创建部门`, visible: false },
        { key: 9, label: `创建人`, visible: false },
        { key: 10, label: `创建时间`, visible: false },
        { key: 11, label: `更新人`, visible: false },
        { key: 12, label: `更新时间`, visible: false },
        { key: 13, label: `删除标志`, visible: false },
]);

const initFormData: ToolingTypeForm = {
  toolingTypeId: undefined,
  toolingTypeCode: undefined,
  toolingTypeName: undefined,
  toolingSpecCode: undefined,
  standardLife: undefined,
  standardWeight: undefined,
  remark: undefined,
}
const data = reactive<PageData<ToolingTypeForm, ToolingTypeQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    toolingTypeId: undefined,
    toolingTypeCode: undefined,
    toolingTypeName: undefined,
    toolingSpecCode: undefined,
    standardLife: undefined,
    standardWeight: undefined,
    params: {
    }
  },
  rules: {
    toolingTypeCode: [
      { required: true, message: "工装类型编号不能为空", trigger: "blur" }
    ],
    toolingTypeName: [
      { required: true, message: "工装类型名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


const processInfoList = ref([]);

/** 查询工序下拉树结构 */
const getProcessInfoListSelect = async () => {
  let res = await getProcessInfoList(null);
  processInfoList.value = res.data;
};

/** 查询载具工装类型列表 */
const getList = async () => {
  loading.value = true;
  const res = await listToolingType(queryParams.value);
  toolingTypeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  toolingTypeFormRef.value?.resetFields();
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ToolingTypeVO[]) => {
  ids.value = selection.map(item => item.toolingTypeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加载具工装类型";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ToolingTypeVO) => {
  reset();
  const _toolingTypeId = row?.toolingTypeId || ids.value[0]
  const res = await getToolingType(_toolingTypeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改载具工装类型";
}

/** 提交按钮 */
const submitForm = () => {
  toolingTypeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.toolingTypeId) {
        await updateToolingType(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addToolingType(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

const submitMaterialForm =async () => {
  buttonLoading.value = true;
    await updateToolingType(form.value).finally(() =>  buttonLoading.value = false);
    proxy?.$modal.msgSuccess("操作成功");
    dialog.visible = false;
    await getList();
  materialDialogOpen.value = false;

}

/** 删除按钮操作 */
const handleDelete = async (row?: ToolingTypeVO) => {
  const _toolingTypeIds = row?.toolingTypeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除载具工装类型编号为"' + _toolingTypeIds + '"的数据项？').finally(() => loading.value = false);
  await delToolingType(_toolingTypeIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('mes/toolingType/export', {
    ...queryParams.value
  }, `toolingType_${new Date().getTime()}.xlsx`)
}

const handleRelationMaterial = async (formData: any) => {
  currentToolingTypeId.value = formData.toolingTypeId;
  currentToolingTypeCode.value = formData.toolingTypeCode;
  currentToolingTypeName.value = formData.toolingTypeName;
  const res = await getToolingType(formData.toolingTypeId);
  Object.assign(form.value, res.data);
  materialDialogOpen.value = true;
};

const handleAddRelationMaterial = () => {
  form.value.typeRelationList = form.value.typeRelationList || [];
  form.value.typeRelationList.push({
    relationInfoId: '',
    materialName: '',
    relationInfoType: '1',
    relationId: undefined
  });
};

const handleDeleteRelationMaterial = () => {
  if (checkedRelationMaterial.value.length === 0) {
    proxy?.$modal.msgError('请先选择要删除的关联物料数据');
  } else {
    form.value.typeRelationList = form.value.typeRelationList.filter(
      item => !checkedRelationMaterial.value.includes(item)
    );
    checkedRelationMaterial.value = [];
  }
};

const handleRelationMaterialSelectionChange = (selection: any[]) => {
  checkedRelationMaterial.value = selection;
};

const rowRelationMaterialIndex = ({ row, rowIndex }: { row: any; rowIndex: number }): string => {
  row.index = rowIndex + 1;
  return '';
};

const openMaterialDialog = (rowIndex: number) => {
  currentMaterialRowIndex.value = rowIndex;
  materialSelectDialogOpen.value = true;
};

const handleMaterialSelection = () => {
  const selectedRow = materialSelectRef.value.tableRef.store.states.currentRow.value;
  if (selectedRow && currentMaterialRowIndex.value !== -1) {
    form.value.typeRelationList[currentMaterialRowIndex.value].relationInfoId = selectedRow.materialId;
    form.value.typeRelationList[currentMaterialRowIndex.value].materialName = selectedRow.materialName;
    form.value.typeRelationList[currentMaterialRowIndex.value].relationInfoType = '1';
  }
  materialSelectDialogOpen.value = false;
};

const handleRelationProcess = async (formData: any) => {
  currentToolingTypeId.value = formData.toolingTypeId;
  currentToolingTypeCode.value = formData.toolingTypeCode;
  currentToolingTypeName.value = formData.toolingTypeName;
  const res = await getToolingType(formData.toolingTypeId);
  Object.assign(form.value, res.data);
  processDialogOpen.value = true;
};

const handleAddRelationProcess = () => {
  form.value.processList = form.value.processList || [];
  form.value.processList.push({
    relationInfoId: '',
    relationInfoType: '2',
    processName: '',
    relationId: undefined
  });
};

const handleDeleteRelationProcess = () => {
  if (checkedRelationProcess.value.length === 0) {
    proxy?.$modal.msgError('请先选择要删除的关联工序数据');
  } else {
    form.value.processList = form.value.processList.filter(
      item => !checkedRelationProcess.value.includes(item)
    );
    checkedRelationProcess.value = [];
  }
};

const handleRelationProcessSelectionChange = (selection: any[]) => {
  checkedRelationProcess.value = selection;
};

const rowRelationProcessIndex = ({ row, rowIndex }: { row: any; rowIndex: number }): string => {
  row.index = rowIndex + 1;
  return '';
};

const handleProcessChange = (rowIndex: number) => {
  const processId = form.value.processList[rowIndex].relationInfoId;
  const process = processInfoList.value.find(item => item.processId === processId);
  if (process) {
    form.value.processList[rowIndex].processName = process.processName;
    form.value.processList[rowIndex].relationInfoId = process.processId;
    form.value.processList[rowIndex].toolingTypeId = currentToolingTypeId.value;
    form.value.processList[rowIndex].relationInfoType = '2';
  }
};

const submitProcessForm = async () => {
  buttonLoading.value = true;
  await updateToolingType(form.value).finally(() => buttonLoading.value = false);
  proxy?.$modal.msgSuccess('操作成功');
  processDialogOpen.value = false;
  await getList();
};

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