<template>
  <div class="page-container column-container">
    <section class="list-part-container">
      <!-- 搜索区域 -->
      <el-form class="list-search-container" :inline="true">
        <el-form-item class="section-title" label="产品信息" />
        <el-form-item label="客户：">
          {{ currentProduct.companyAlias }}
        </el-form-item>
        <el-form-item label="图号：">
          {{ currentProduct.drawingNumber }}
        </el-form-item>
        <el-form-item label="规格：">
          {{ currentProduct.specification }}
        </el-form-item>
        <el-form-item label="产品描述：">
          {{ currentProduct.description }}
        </el-form-item>
        <el-form-item> </el-form-item>
        <el-form-item class="section-title" label="工艺版本：">
          {{ currentTechnological.productVersion }}
        </el-form-item>
        <el-form-item class="section-title" label="当前工序：">
          <el-select-v2
            v-model="technologicalDetailId"
            clearable
            :options="technologicalProcessDetailsList"
            placeholder="请选择工序"
            style="width: 160px"
            @change="handleDetailsChange"
          />
        </el-form-item>
      </el-form>
    </section>
    <div class="page-container row-container">
      <section class="list-part-container" style="flex: 1">
        <div class="list-btns-container">
          <el-button
            type="success"
            v-hasPermi="['business:standards:add']"
            @click="handelAdd()"
            >新增
          </el-button>
          <el-button
            type="danger"
            v-hasPermi="['business:standards:remove']"
            :disabled="multiple"
            @click="handleDelete"
            >删除
          </el-button>
        </div>
        <div class="el-table-container">
          <!-- 列表区 -->
          <div class="el-table-inner-container">
            <el-table
              ref="standardsTable"
              v-loading="loading"
              row-key="id"
              highlight-current-row
              @current-change="handleChange"
              :data="standardsList"
              @selection-change="handleSelectionChange"
              height="600px"
            >
              <el-table-column type="selection" width="40" align="center" />
              <el-table-column
                type="index"
                label="行号"
                width="50"
                align="center"
              />

              <el-table-column label="检查标准" prop="standard" align="center">
                <template #default="scope">
                  <span v-if="!scope.row.editStatus">{{
                    scope.row.standard
                  }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.standard"
                    placeholder="请输入检查标准"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="检查仪器"
                prop="instrument"
                align="center"
                width="200"
              >
                <template #default="scope">
                  <span v-if="!scope.row.editStatus">{{
                    scope.row.instrument
                  }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.instrument"
                    placeholder="请输入检查仪器"
                  />
                </template>
              </el-table-column>

              <template
                v-for="column in sortCheckStandardList"
                :key="column.id"
              >
                <el-table-column
                  :prop="column.code"
                  :label="column.name"
                  width="60"
                  align="center"
                >
                  <template #default="scope">
                    <!-- {{ getSortCheck(scope.row.checkStandardList,column.inspectionInstructionId) }} -->
                    <el-checkbox
                      :disabled="!scope.row.editStatus"
                      v-model="scope.row[column.code]"
                    />
                  </template>
                </el-table-column>
              </template>

              <el-table-column
                fixed="right"
                width="200"
                label="操作"
                align="center"
              >
                <template #default="scope">
                  <el-button-group
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      flex-wrap: nowrap;
                    "
                  >
                    <el-button
                      v-if="!scope.row.editStatus"
                      link
                      type="primary"
                      v-hasPermi="['business:standards:edit']"
                      @click="handelEdit(scope.row, 'edit')"
                      >编辑
                    </el-button>
                    <el-button
                      v-if="scope.row.editStatus"
                      link
                      type="success"
                      plain
                      v-hasPermi="['business:standards:add']"
                      @click="handlePreview(scope.row)"
                      >保存</el-button
                    >

                    <el-button
                      v-if="scope.row.editStatus"
                      link
                      type="warning"
                      v-hasPermi="['business:standards:edit']"
                      @click="handelEdit(scope.row, 'cancel')"
                      >取消
                    </el-button>

                    <el-button
                      v-if="!scope.row.editStatus"
                      link
                      type="danger"
                      v-hasPermi="['business:standards:remove']"
                      @click="handleDelete(scope.row)"
                      >删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 分页 -->
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryparams.pageNum"
          v-model:limit="queryparams.pageSize"
          @pagination="getStandards"
        />
      </section>
    </div>
  </div>
</template>
<script setup name="drawingDetails">
import { ref } from "vue";
import { getToken } from "@/utils/auth";
import { listCheck, listRoleCheck } from "@/api/business/check";
import {
  listStandards,
  addStandards,
  delStandards,
} from "@/api/business/standards";

import useUserStore from "@/store/modules/user";
import { getTechnological, getById } from "@/api/business/product";
import { getTechnologicalProcessDetails } from "@/api/business/technologicalProcessDetail";

const drawingUrl = ref("");
const { proxy } = getCurrentInstance();
const total = ref(0);
const route = useRoute();
const coverName = ref("");
const editStatus = ref(false);
const currentProduct = ref({});
const currentTechnological = ref({});
const currentTechnologicalDetail = ref({});
const technologicalProcessList = ref([]);
const technologicalProcessDetailsList = ref([]);
const technologicalDetailId = ref(null);
const repeatingDrawings = ref([]);
const standardsTable = ref(null);
const loading = ref(false);
const standardsList = ref([]);
const productId = ref(null);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const processCode = ref(null);
const processId = ref(null);
const productVersion = ref(null);
const sortCheckStandardList = ref([]);
/** 查询对象 */
const data = reactive({
  queryparams: {
    pageNum: 1,
    pageSize: 10,
    technologicalProcessDetailId: null,
  },
  form: {
    pageNum: 1,
    pageSize: 10,
    parentId: null,
    technologicalProcessDetailId: null,
    groupDetailList: [],
    code: "",
    remark: "",
    type: false,
  },
  rules: {
    technologicalProcessDetailId: [
      { required: true, message: "工序不能为空", trigger: "blur" },
    ],
  },
});
const { form, rules, queryparams } = toRefs(data);
const detailsRow = {
  standard: "",
  instrument: "",
  editStatus: true,
};
function getList() {
  loading.value = true;
  productId.value = route.params.productId;
  productVersion.value = route.params.productVersion;

  if (!processCode.value && route.params.processCode) {
    processCode.value = route.params.processCode;
  } else {
    technologicalDetailId.value = null;
  }
  //查询产品
  getById(productId.value).then((resMsg) => {
    if (resMsg.code == 200) {
      currentProduct.value = resMsg.data;
    }
  });

  //查询工艺版本
  getTechnological({ productId: productId.value }).then((res) => {
    if (res.code == 200) {
      technologicalProcessList.value = res.data;
      //版本下拉框默认值
      currentTechnological.value.productVersion = productVersion.value;

      //查询工艺工序
      getTechnologicalProcessDetails({
        technologyVersion: currentTechnological.value.productVersion,
        productId: productId.value,
      }).then((response) => {
        if (response.code == 200) {
          technologicalProcessDetailsList.value = response.data;
          if (
            processCode.value !== undefined &&
            processCode.value !== null &&
            processCode.value !== "undefined"
          ) {
            technologicalDetailId.value = response.data.find(
              (detail) => detail.code == processCode.value
            ).value;
            currentTechnologicalDetail.value.id = response.data.find(
              (detail) => detail.code === processCode.value
            ).value;
            processId.value = response.data.find(
              (detail) => detail.code == processCode.value
            ).processId;
          } else {
            technologicalDetailId.value = null;
          }
          getStandards();
        }
      });
    }
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  console.log(ids.value);
}

function handleChange(row) {}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  console.log(ids.value);
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      return delStandards(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功！");
    })
    .catch(() => {});
}
function handelAdd() {
  //判断是否处于编辑状态，如果处于编辑状态不可新增
  if (editStatus.value) {
    proxy.$modal.msgError("请先保存数据");
    return;
  }
  editStatus.value = true;
  const newDetail = JSON.parse(JSON.stringify(detailsRow));
  sortCheckStandardList.value.forEach((column) => {
    newDetail[column.code] = ""; // 假设默认值是空字符串，根据实际情况调整
  });

  // 将新行添加到standardsList中
  standardsList.value.push(newDetail);
}
/**获取图纸列表 */
function getStandards() {
  loading.value = true;
  queryparams.value.productId = productId.value;
  queryparams.value.productVersion = currentTechnological.value.productVersion;
  queryparams.value.processCode = processCode.value;
  // if (currentTechnologicalDetail.value.id !== undefined && currentTechnologicalDetail.value.id !== 'undefined') {
  //     queryparams.value.technologicalProcessDetailId = currentTechnologicalDetail.value.id

  // }
  listStandards(queryparams.value).then((res) => {
    if (res.code == 200) {
      standardsList.value = res.rows;
      console.log(1225, res.rows);
      if (res.rows.length > 0) {
        proxy.$refs.standardsTable.setCurrentRow(res.rows[0]);
      } else {
        drawingUrl.value = null;
      }
      total.value = res.total;
    }
    loading.value = false;
  });
  listRoleCheck({}).then((res) => {
    if (res.code == 200) {
      sortCheckStandardList.value = res.data;
    }
  });
}

function handelEdit(row, type) {
  if (type == "edit") {
    if (editStatus.value) {
      proxy.$modal.msgError("请先保存数据");
      return;
    }
  }
  row.editStatus = !row.editStatus;
  console.log(row);

  if (type == "cancel" && !row.id) {
    standardsList.value = standardsList.value.filter((item) => item !== row);
  }
  if (type == "cancel") {
    editStatus.value = false;
    getList();
  }
}

/**审核 */
function handlePreview(row) {
  if (!row.standard) {
    proxy.$modal.msgError("请输入检查标准");
  } else {
    var item = row;
    item.productId = productId.value;
    item.processCode = processCode.value;
    item.productVersion = productVersion.value;
    item.processId = processId.value;
    addStandards(row).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功");
        reset();
        getList();
        editStatus.value = false;
      }
    });
  }
}
function reset() {
  form.value = {
    pageNum: 1,
    pageSize: 10,
    code: null,
    remark: null,
    groupDetailList: [],
    url: null,
    drawingName: null,
    identification: 0,
    markD: 0,
    type: false,
  };
  currentTechnologicalDetail.value = {};
  coverName.value = "";
  repeatingDrawings.value = [];
  proxy.resetForm("drawingRef");
}

/**工序选择change事件 */
function handleDetailsChange() {
  if (technologicalDetailId.value) {
    var matchingDetail = technologicalProcessDetailsList.value.find(
      (detail) => detail.value === technologicalDetailId.value
    );
    currentTechnologicalDetail.value.id =
      technologicalDetailId.value == undefined
        ? null
        : technologicalDetailId.value;
    processCode.value = matchingDetail.code;
    processId.value = matchingDetail.processId;
  } else {
    processCode.value = null;
    drawingUrl.value = null;
  }
  getStandards();
}

getList();
</script>

<style scoped>
:deep(.el-form-item .el-form-item__label) {
  font-size: 14px !important;
  padding-right: 0 !important;
}

:deep(#list-search-container .el-form-item--default .el-form-item__content) {
  line-height: 32px;
  font-size: 18px;
}
</style>