<template>
  <div class="container1">
    <div class="databox">
      <div class="box">
        <div class="title">
          <div class="bg"></div>
          配置列表
        </div>
        <div class="info">
          <el-table
            :data="tableData"
            border
            :style="{ height: maxHeight - 30 + 'px' }"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="operationName" label="工序名称" />
            <el-table-column prop="field" label="参数项" />
            <el-table-column prop="chart" label="控制图" />
            <el-table-column prop="ruleContent" label="规则内容" width="200" />
            <el-table-column prop="unit" label="参数单位" />
            <el-table-column
              align="center"
              width="160"
              prop=""
              label="操作"
              id="opear"
            >
              <template #default="{ row }">
                <el-button
                  v-if="addRuleStatus"
                  class="btn"
                  link
                  @click="editSubmit(row)"
                  >编辑</el-button
                >
                <el-button v-else class="btn" link @click="cancelEdit"
                  >取消</el-button
                >
                <el-button link @click="deleteRules(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>
      <div class="box">
        <div class="title">
          <div class="bg"></div>
          预警规则配置
        </div>
        <div class="info">
          <div class="taskInfo">
            <span class="item"
              >当前规则编辑状态：{{ addRuleStatus ? "新增" : "编辑" }}</span
            >
            <span class="item"
              >工序名称：{{
                !addRuleStatus
                  ? editRow.operationName
                  : store.spcTaskObj.operationName
              }}</span
            >
            <span class="item">
              参数项：{{
                !addRuleStatus ? editRow.field : store.spcTaskObj.param
              }}
            </span>
          </div>
          <div class="form" :key="formKey">
            <el-scrollbar
              :style="{ height: maxHeight - 100 + 'px' }"
              style="padding: 20px"
            >
              <template v-for="(item, index) in formData" :key="index">
                <el-form
                  :ref="
                    (el) => {
                      if (item) {
                        formRefs.push(el);
                      }
                    }
                  "
                  :model="item"
                  style="display: flex; align-items: center"
                >
                  <el-form-item>
                    <div style="display: flex; align-items: center">
                      <span class="itemText" style="width: 50px"
                        >条件{{ index + 1 }}：</span
                      >
                    </div>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        trigger: 'change',
                      },
                    ]"
                    prop="sum1type"
                  >
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        margin-right: 10px;
                      "
                    >
                      <el-select
                        v-model="item.sum1type"
                        style="width: 160px"
                        class="formItem"
                        placeholder="请选择规则点类型"
                      >
                        <el-option
                          v-for="(item, index) in sum1Options"
                          :key="index"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </div>
                  </el-form-item>
                  <el-form-item
                    v-if="item.sum1type == '连续'"
                    :rules="[
                      {
                        required: true,
                        trigger: 'change',
                      },
                    ]"
                    prop="sum1"
                    ><div
                      style="
                        display: flex;
                        align-items: center;
                        margin-right: 10px;
                      "
                    >
                      <el-input-number
                        class="formItem"
                        style="width: 80px"
                        v-model="item.sum1"
                        :min="1"
                        :precision="0"
                        controls-position="right"
                      /><span class="itemText">个点</span>
                    </div>
                  </el-form-item>
                  <el-form-item
                    v-if="item.sum1type == '连续'"
                    prop="sum2"
                    :rules="[
                      {
                        validator: validateSum2,
                        required: true,
                        trigger: 'change',
                        sum1: item.sum1,
                        message: '应小于或等于前连续点数',
                      },
                    ]"
                    ><div style="display: flex; align-items: center">
                      <span style="margin-left: 0" class="itemText">中的</span>
                      <el-input-number
                        class="formItem"
                        style="width: 80px"
                        v-model="item.sum2"
                        :min="1"
                        :precision="0"
                        controls-position="right"
                      /><span class="itemText">个点</span>
                    </div>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        trigger: 'change',
                      },
                    ]"
                    prop="judgeType"
                  >
                    <el-select
                      class="formItem"
                      style="width: 170px; margin-right: 5px"
                      v-model="item.judgeType"
                      placeholder="请选择判定类型"
                    >
                      <el-option
                        v-for="(item, index) in item.sum1type == '连续'
                          ? judgeTypeOptions2
                          : judgeTypeOptions1"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: true,
                        trigger: 'change',
                      },
                    ]"
                    prop="numerical"
                    v-if="
                      item.judgeType == '大于' ||
                      item.judgeType == '小于' ||
                      item.judgeType == '等于'
                    "
                  >
                    <el-select
                      class="formItem"
                      style="width: 170px; margin-right: 5px"
                      v-model="item.numerical"
                      placeholder="请选择择值范围"
                    >
                      <el-option
                        v-for="(item, index) in numericalOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    :rules="[
                      {
                        required: false,
                        trigger: 'change',
                      },
                    ]"
                    label=""
                  >
                    <el-button
                      v-if="index == formData.length - 1"
                      type="success"
                      class="btn"
                      @click="addRule"
                      style="margin-left: 5px"
                      >添加</el-button
                    >
                    <el-button
                      v-if="formData.length > 1"
                      type="warning"
                      class="btn"
                      style="margin-left: 5px"
                      @click="deleteRule(index)"
                      >删除</el-button
                    >
                  </el-form-item>
                </el-form>
                <div class="titleText" v-if="index < formData.length - 1">
                  且
                </div>
              </template>
              <el-form style="display: flex; align-items: center">
                <el-form-item>
                  <div style="display: flex; align-items: center">
                    <span class="itemText" style="width: 80px">预警提示：</span>
                    <el-input
                      class="formItem"
                      style="width: 400px"
                      v-model="ruleTips"
                    />
                  </div> </el-form-item
              ></el-form>
            </el-scrollbar>
          </div>
          <div class="btns">
            <el-button type="primary" class="btn" @click="tosubmit"
              >提交</el-button
            >
            <el-button class="btn" @click="toCencel">取消</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="预警规则编辑"
      width="500"
      :before-close="handleClose"
    >
      <div class="dialogTitle">请确认规则修改为：</div>
      <div class="contentTitle">{{ itemContent }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="sumitRule">确定</el-button>
          <el-button @click="dialogVisible = false"> 取消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useSpcStore } from "@/store";
import { getRuleData, addRuleData, deleteRuleData } from "@/api/spc";
import router from "@/router";
const store = useSpcStore();
const dialogVisible = ref(false);
const ruleTips = ref("");
const formRefs = ref([]);
const formData = ref([]);
const formKey = ref(false);
const itemObj = {};
const addRule = () => {
  formRefs.value = [];
  formData.value.push({ ...itemObj });
};
const toCencel = () => {
  reset();
  router.back();
};
const editRow = ref({});
const validateSum2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("Please input the sum2"));
  } else {
    if (value <= rule.sum1) {
      callback();
    } else {
      callback(new Error("Please check the sum2"));
    }
  }
};

const deleteRule = (index) => {
  formRefs.value = [];
  formData.value.splice(index, 1);
  ElMessage.success("删除成功");
};
const deleteRules = async (id) => {
  const { code } = await deleteRuleData({ id });
  if (code == "200") {
    ElMessage.success("操作成功");
    reset();
  }
};
const sumitRule = () => {
  addSubmit();
  reset();
  dialogVisible.value = false;
};
const reset = () => {
  formKey.value = !formKey.value;
  getData();
  refsData();
  ruleTips.value = "";
  editRow.value = {};
  addRuleStatus.value = true;
};
const addRuleStatus = ref(true);
const editSubmit = (row) => {
  editRow.value = { ...row };
  formData.value = JSON.parse(editRow.value.ruleExpression);
  ruleTips.value = editRow.value.ruleTips;
  addRuleStatus.value = false;
};
const sum1Options = [
  {
    label: "连续",
    value: "连续",
  },
  {
    lable: "单点",
    value: "单点",
  },
];
const judgeTypeOptions1 = [
  {
    label: "大于",
    value: "大于",
  },
  {
    label: "小于",
    value: "小于",
  },
  {
    label: "等于",
    value: "等于",
  },
];
const judgeTypeOptions2 = [
  {
    label: "大于",
    value: "大于",
  },
  {
    label: "小于",
    value: "小于",
  },
  {
    label: "等于",
    value: "等于",
  },
  {
    label: "递增",
    value: "递增",
  },
  {
    label: "递减",
    value: "递减",
  },
  {
    label: "升降",
    value: "升降",
  },
];
const numericalOptions = [
  {
    label: "上限值",
    value: "上限值",
  },
  {
    label: "下限值",
    value: "下限值",
  },
  {
    label: "标准值",
    value: "标准值",
  },
  {
    label: "三分之一上限值",
    value: "三分之一上限值",
  },
  {
    label: "三分之二上限值",
    value: "三分之二上限值",
  },
  {
    label: "三分之一下限值",
    value: "三分之一下限值",
  },
  {
    label: "三分之二下限值",
    value: "三分之二下限值",
  },
  // {
  //   label: "上限范围C",
  //   value: "上限范围C",
  // },
  // {
  //   label: "上限范围B",
  //   value: "上限范围B",
  // },
  // {
  //   label: "上限范围A",
  //   value: "上限范围A",
  // },
  // {
  //   label: "下限范围C",
  //   value: "下限范围C",
  // },
  // {
  //   label: "下限范围B",
  //   value: "下限范围B",
  // },
  // {
  //   label: "下限范围A",
  //   value: "下限范围A",
  // },
];
const currentOption = reactive({
  total: 0,
  page: 1,
  limit: 10,
  pageSizes: [10],
});
const itemContent = ref("");
const setContent = () => {
  itemContent.value = "";
  formData.value.forEach((item, index) => {
    if (item.sum1type == "单点") {
      itemContent.value =
        itemContent.value +
        `当${item.sum1type}${item.judgeType}${item.numerical}`;
    } else {
      itemContent.value =
        itemContent.value +
        `当${item.sum1type}的${item.sum1}个点中的${item.sum2}个点${item.judgeType}${item.judgeType == "大于" || item.judgeType == "小于" || item.judgeType == "等于" ? item.numerical : ""}`;
    }
    if (index < formData.value.length - 1) {
      itemContent.value = itemContent.value + "且";
    }
    if (index == formData.value.length - 1) {
      itemContent.value = itemContent.value + "时预警";
    }
  });
};
const tableData = ref([]);
const cancelEdit = () => {
  formKey.value = !formKey.value;
  refsData();
  ruleTips.value = "";
  editRow.value = {};
  addRuleStatus.value = true;
};
const tosubmit = async () => {
  //首先进行动态校验
  const promiseArray = ref([]);
  formRefs.value.forEach((item) => {
    if (item) {
      promiseArray.value.push(
        new Promise((resolve, reject) => {
          item.validate((valid, fields) => {
            if (valid) {
              resolve();
            } else {
              reject();
            }
          });
        })
      );
    }
  });

  Promise.all(promiseArray.value)
    .then(() => {
      //校验成功 进入下层逻辑
      setContent();
      dialogVisible.value = true;
    })
    .catch(() => {
      //校验失败
      ElMessage.error("请检查表单红项填写");
    });
};
const addSubmit = async () => {
  //编辑和新加都在此调用（依靠id是否传递区分）
  const { data, code } = await addRuleData({
    chart: store.spcTaskObj.chart,
    field: store.spcTaskObj.param,
    label: store.spcTaskObj.operationName,
    operationCode: store.spcTaskObj.operationCode,
    operationName: store.spcTaskObj.operationName,
    ruleContent: itemContent.value,
    ruleExpression: JSON.stringify(formData.value),
    ruleTips: ruleTips.value,
    taskCode: store.spcTaskObj.taskCode,
    unit: store.spcTaskObj.unit,
    id: addRuleStatus.value == true ? null : editRow.value.id,
  });
  if (code == "200") {
    ElMessage.success("操作成功");
    getData();
  }
};
const getData = async () => {
  const { data, msg } = await getRuleData({
    pageNo: currentOption.page,
    pageSize: currentOption.limit,
    taskCode: store.spcTaskObj.taskCode,
  });
  tableData.value = data.records;
  currentOption.total = data.totalCount;
};
const maxHeight = ref(null);
const setHeight = () => {
  maxHeight.value = document.querySelector(".info").clientHeight;
};
const refsData = () => {
  formRefs.value = [];
  formData.value = [{}];
};
onMounted(() => {
  setHeight();
  getData();
  refsData();
});
</script>

<style lang="scss" scoped>
.dialogTitle {
  font-size: 15px;
  font-weight: bolder;
}

.contentTitle {
  margin: 10px;
  font-size: 16px;
  font-weight: 500;
}
.el-form-item {
  margin-bottom: 10px !important;
}
.titleText {
  font-size: 14px;
  font-weight: 500;
  color: #67c23a;
  padding-left: 40px;
  margin: 5px;
}
.container1 {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: white;
  .infobox {
    width: 200px;
    display: flex;
    flex-direction: column;
  }
  .databox {
    flex: 1;
    border-left: 2px solid #00000010;
    height: 100%;
    .box {
      height: calc(50%);
      padding: 5px 20px;
      display: flex;
      flex-direction: column;
      .title {
        height: 30px;
        display: flex;
        align-items: center;
      }
      .info {
        flex: 1;
        display: flex;
        flex-direction: column;
        .taskInfo {
          height: 30px;
          .item {
            font-size: 15px;
            margin-right: 20px;
          }
        }
        .form {
          flex: 1;
          border: 1px dashed #00000020;
          border-radius: 16px;

          .itemText {
            margin: 0 5px;
          }
          .formItem {
            display: inline-block;
          }
        }
        .btns {
          height: 80px;
          display: flex;
          align-items: center;
          justify-content: center;
          .btn {
            height: 40px;
          }
        }
      }
    }
    .boxstitle {
      height: 80px;
      padding: 5px 20px;
      display: flex;
      flex-direction: column;
      .boxtitle {
        height: 30px;
        display: flex;
        align-items: center;
      }
      .boxinfo {
        display: flex;
        .item {
          width: 260px;
          display: flex;
          align-items: center;
          margin: 10px;

          .lable {
            margin-right: 5px;
            white-space: nowrap;
            font-size: 15px;
          }
        }
      }
    }
  }
}
.submitBox {
  height: 60vh;
  display: flex;
  flex-direction: column;
  .submitInfo {
    flex: 1;

    .text {
      font-size: 16px;
      font-weight: 500;
    }
  }
  .btns {
    height: 60px;
  }
}
</style>
