<template>
  <div class="container1">
    <div class="header" v-show="!addStatus && !editStatus">
      <Search
        :searchOptions="searchForm"
        ref="searchRef"
        @data-list="getData"
        @reset-list="resetData"
      />
    </div>
    <div class="table" v-if="!addStatus && !editStatus">
      <el-button
        type="primary"
        size="small"
        class="btn"
        style="margin-bottom: 10px"
        @click="toAdd"
        >新增</el-button
      >
      <el-table :data="tableData" border>
        <el-table-column align="center" prop="taskCode" label="任务编号" />
        <el-table-column align="center" prop="prodtModel" label="产品型号" />
        <el-table-column align="center" prop="prodtCode" label="产品编号" />
        <el-table-column align="center" prop="operationName" label="工序名称" />
        <el-table-column align="center" prop="source" label="采集数据源" />
        <!--        <el-table-column prop="param" label="控制参数" />-->
        <!--        <el-table-column prop="chart" label="控制图" />-->
        <!--        <el-table-column prop="address" label="预警规则">-->
        <!--          <template #default="{ row }">-->
        <!--            <el-button-->
        <!--              type="primary"-->
        <!--              class="btn"-->
        <!--              style="height: 25px"-->
        <!--              link-->
        <!--              @click="toRuler(row)"-->
        <!--              >编辑</el-button-->
        <!--            >-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          align="center"
          prop="processCount"
          label="工序采集点数"
        />
        <!--        <el-table-column prop="centralValue" label="中心值" />-->
        <!--        <el-table-column prop="upperLimit" label="上限" />-->
        <!--        <el-table-column prop="floor" label="下限" />-->
        <el-table-column align="center" prop="created" label="创建时间" />
        <el-table-column
          align="center"
          width="160"
          prop=""
          label="操作"
          id="opear"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              class="btn"
              style="height: 25px"
              @click="toEdit(row)"
              size="small"
              >修改</el-button
            >
            <el-button
              type="info"
              class="btn"
              style="height: 25px"
              size="small"
              @click="toDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :total="currentOption.total"
        :page="currentOption.page"
        :limit="currentOption.limit"
        :pageSizes="currentOption.pageSizes"
        v-model:page="currentOption.page"
        v-model:limit="currentOption.limit"
        @pagination="getData"
      />
    </div>
    <div v-if="addStatus || editStatus" class="formView">
      <div class="formTitle">
        {{ addStatus ? "新增任务" : "修改任务" }}
      </div>
      <el-scrollbar style="height: calc(100% - 60px)">
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="auto"
          class="formStyle"
        >
          <el-form-item label="任务编号" prop="taskCode">
            <el-input v-model="formData.taskCode" />
          </el-form-item>
          <el-form-item label="产品型号" prop="Index1">
            <el-select
              v-model="formData.Index1"
              @change="
                (value) => {
                  taskChange(value);
                }
              "
            >
              <el-option
                v-for="(item, index) in opInfoData"
                :key="index"
                :label="item.prodtModel"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品编号" prop="prodtCode">
            <el-input :disabled="true" v-model="formData.prodtCode" />
          </el-form-item>
          <el-form-item label="工序名称" prop="Index2">
            <el-select v-model="formData.Index2">
              <el-option
                v-for="(item, index) in opOptions"
                :key="index"
                :label="item.dictLabel"
                :value="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集数据来源" prop="source">
            <el-select v-model="formData.source">
              <el-option label="自动" value="自动" />
              <el-option label="手动" value="手动" />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="控制参数" prop="param">-->
          <!--            <el-input v-model="formData.param" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="控制图" prop="chart">-->
          <!--            <el-input :disabled="true" v-model="formData.chart" />-->
          <!--          </el-form-item>-->
          <el-form-item label="工序采集点数" prop="processCount">
            <el-input-number
              v-model="formData.processCount"
              :min="1"
              :step="1"
            />
          </el-form-item>
          <!--          <el-form-item label="上限" prop="upperLimit">-->
          <!--            <el-input-number v-model="formData.upperLimit" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="下限" prop="floor">-->
          <!--            <el-input-number v-model="formData.floor" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="中心值" prop="centralValue">-->
          <!--            <el-input-number-->
          <!--              :min="formData.floor"-->
          <!--              :max="formData.upperLimit"-->
          <!--              v-model="formData.centralValue"-->
          <!--            />-->
          <!--          </el-form-item>-->
        </el-form>
        <div style="display: flex; justify-content: space-evenly">
          <el-button
            type="primary"
            size="small"
            style="margin-top: 10px"
            class="btn"
            @click="toSubmit"
            >提交</el-button
          >
          <el-button
            type="info"
            size="small"
            style="margin-top: 10px"
            class="btn"
            @click="toCancel"
            >取消</el-button
          >
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import Search from "@/components/Search/index.vue";
import { useDictionaryStore, useSpcStore } from "@/store";
import {
  getTableData,
  getBaseData,
  add,
  updateData,
  deleteData,
} from "@/api/spc";
import { ElMessage, ElMessageBox } from "element-plus";
import { DatetimeFormat } from "vue-i18n";
defineOptions({
  name: "SPCrules",
});
const store = useSpcStore();
const addStatus = ref(false);
const editStatus = ref(false);
const router = useRouter();
const formData = ref({
  source: "手动",
  chart: "X-R",
});
const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10, 20, 30, 40, 50],
});
const showStatus = ref(true);
const tableData = ref([]);
const searchRef = ref(null);
const searchForm = [
  {
    label: "创建时间",
    prop: "createds",
    type: "daterange",
  },
  {
    label: "任务编号",
    prop: "taskCode",
    type: "input",
  },
  {
    label: "产品型号",
    prop: "prodtModel",
    type: "input",
  },
];

const maxHeight = ref(null);
const setHeight = () => {
  maxHeight.value = document.querySelector(".table").clientHeight;
};
const opInfoData2 = computed(() => {
  if (formData.value.Index1 != null) {
    return opInfoData.value[formData.value.Index1].operations;
  } else {
    return [];
  }
});
const toCancel = () => {
  reset();
};
const toRuler = (row) => {
  store.spcTaskObj = row;
  router.push({ name: "SPCrules" });
};
const getData = async (obj) => {
  const { data, code } = await getTableData({
    ...searchRef.value.searchForm,
    pageNo: currentOption.page,
    pageSize: currentOption.limit,
  });
  if (code == "200") {
    tableData.value = data.records;
    currentOption.total = data.totalCount;
  }
};
const ruleFormRef = ref(null);
const { dicts } = useDictionaryStore();
const opOptions = ref([...dicts.spc_operation]);

const rules = {
  taskCode: [
    {
      required: true,
      trigger: "change",
      message: "请输入任务编号",
    },
  ],
  Index1: [
    {
      required: true,
      message: "请选择产品型号",
      trigger: "change",
    },
  ],
  Index2: [
    {
      required: true,
      message: "请选择工序名称",
      trigger: "change",
    },
  ],
  operationName: [
    {
      required: true,
      trigger: "change",
      message: "请选择工序名称",
    },
  ],
  source: [
    {
      required: true,

      trigger: "change",
    },
  ],
  chart: [
    {
      required: true,

      trigger: "change",
    },
  ],
  param: [
    {
      required: true,

      trigger: "change",
    },
  ],
  unit: [
    {
      required: true,

      trigger: "change",
    },
  ],
  processCount: [
    {
      required: true,

      trigger: "change",
    },
  ],
  centralValue: [
    {
      required: true,

      trigger: "change",
    },
  ],
  upperLimit: [
    {
      required: true,

      trigger: "change",
    },
  ],
  floor: [
    {
      required: true,

      trigger: "change",
    },
  ],
};
const opInfoData = ref([]);
const toAdd = () => {
  addStatus.value = true;
  formData.value.taskCode = "RW" + getCurrentTime();
};
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  return `${year}${month}${day}${hours}${minutes}${seconds}`;
};
const setEditFormData = (row) => {
  opInfoData.value.forEach((item, index) => {
    if (item.prodtCode == row.prodtCode) {
      formData.value.Index1 = index;
    }
  });
  opOptions.value.forEach((item, index) => {
    if (item.dictLabel == row.operationName) {
      formData.value.Index2 = index;
    }
  });
};
const toEdit = (row) => {
  const data = JSON.parse(JSON.stringify(row));
  formData.value = data;
  //设置index1 index2
  setEditFormData(data);
  editStatus.value = true;
};
const toDelete = async (id) => {
  ElMessageBox.confirm("是否删除所选中数据？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { code } = await deleteData({ id });
    if (code == "200") {
      ElMessage.success("操作成功");
      getData();
    }
  });
};
const reset = () => {
  formData.value = {
    source: "手动",
    chart: "X-R",
  };
  addStatus.value = false;
  editStatus.value = false;
  currentOption.value = {
    total: 0,
    page: 1,
    limit: 10,
    pageSizes: [10, 20, 30, 40, 50],
  };
};

const resetData = () => {
  searchRef.value.searchForm = {};
  getData();
};

const toSubmit = async () => {
  if (addStatus.value) {
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const { data, code } = await add({
          chart: formData.value.chart,
          operationCode: opOptions.value[formData.value.Index2].dictValue,
          operationName: opOptions.value[formData.value.Index2].dictLabel,
          prodtCode: opInfoData.value[formData.value.Index1].prodtCode,
          prodtModel: opInfoData.value[formData.value.Index1].prodtModel,
          prodtName: opInfoData.value[formData.value.Index1].prodtName,
          unit: opInfoData.value[formData.value.Index1].unit,
          param: formData.value.param,
          source: formData.value.source,
          processCount: formData.value.processCount,
          centralValue: formData.value.centralValue,
          upperLimit: formData.value.upperLimit,
          floor: formData.value.floor,
          taskCode: formData.value.taskCode,
        });
        if (code == "200") {
          ElMessage.success("添加成功！");
          await reset();
          getData();
        }
      } else {
        ElMessage.error("请检查表单信息");
      }
    });
  } else {
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const { data, code } = await updateData({
          ...formData.value,
          operationCode: opOptions.value[formData.value.Index2].dictValue,
          operationName: opOptions.value[formData.value.Index2].dictLabel,
          prodtCode: opInfoData.value[formData.value.Index1].prodtCode,
          prodtModel: opInfoData.value[formData.value.Index1].prodtModel,
          prodtName: opInfoData.value[formData.value.Index1].prodtName,
          unit: opInfoData.value[formData.value.Index1].unit,
        });
        if (code == "200") {
          ElMessage.success("修改成功！");
          await reset();
          getData();
        }
      } else {
        ElMessage.error("请检查表单信息");
      }
    });
  }
};
const getBaseDatas = async () => {
  const { data, code } = await getBaseData();
  opInfoData.value = data;
};
const taskChange = (value) => {
  formData.value.prodtCode = opInfoData.value[value].prodtCode;
};
onMounted(() => {
  setHeight();
  getBaseDatas();
  getData();
});
</script>

<style scoped lang="scss">
.container1 {
  background-color: white;
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;

  .header {
    width: 100%;
    height: auto;
  }

  .table {
    flex: 1;
    padding-bottom: 20px;
  }

  .formView {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .formTitle {
      text-align: center;
      font-size: 20px;
      margin-bottom: 20px;
    }

    .formStyle {
      width: 400px;
    }
  }
}
</style>
