<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, nextTick } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import {
  postAddDimension,
  getDimensionRemove,
  postUpdateDept,
  getRemove
} from "@/api/dimension";
import { postUpdate } from "@/api/templateInfo";
import type { DrawerProps, FormItemProps, FormProps } from "element-plus";
// const itemLabelPosition = ref<FormItemProps["labelPosition"]>("");
const drawer = ref(false);
const $route = useRoute();
const $emit = defineEmits(["handClick"]);
const dalongTitle = ref("");
const direction = ref<DrawerProps["direction"]>("rtl");
const ruleFormRef = ref();
const dimWeight = ref(false);
const oldIndexList = reactive({
  // 分数
  indLimitScore: []
});
// 分数
const formLabelAlign = reactive({
  id: "",
  list: [
    {
      id: "",
      dimName: "",
      dimWeight: "",
      mode: ""
    }
  ],
  dimName: "",
  dimWeight: 0,
  dimWeightBol: false,
  mode: 1,
  showIndicRemark: 0,
  showScoreRule: 1,
  showDatasource: 0,
  showTargetValue: 0,
  showFinalValue: 0,
  showChallengeValue: 0,
  showStartValue: 0,
  showRemark: 0,
  remark: "",
  tpId: ""
});
// 存储指标变量，修改指标最高值时使用
const changeIndexList = ref([]);
const handleClose = () => {
  Object.assign(formLabelAlign, {});
  ruleFormRef.value.resetFields();
  drawer.value = false;
};
function confirmClick() {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (dalongTitle.value == "编辑") {
        postUpdateDeptApi();
        postUpdateApi();
      } else {
        postAddDimensionApi();
      }
    }
  });
}
const titleName = ref("");
const indexList = ref([]);
const open = (row: any, title: string, order: number) => {
  Object.assign(formLabelAlign, {});
  oldIndexList.indLimitScore = [];
  dalongTitle.value = title;
  if (title == "新建") {
    titleName.value = "新建考核维度";
    Object.assign(formLabelAlign, {
      tpId: row.id ? row.id : $route.query.id,
      list: [],
      dimName: "",
      dimWeight: 0,
      mode: 1,
      showIndicRemark: 0,
      showScoreRule: 1,
      showDatasource: 0,
      showTargetValue: 0,
      showFinalValue: 0,
      showChallengeValue: 0,
      showStartValue: 0,
      showRemark: 0,
      remark: "",
      order: order
    });
  }
  if (title == "编辑") {
    titleName.value = "编辑考核维度";
    // 深拷贝对象防止父子通信的双向绑定
    Object.assign(
      formLabelAlign,
      JSON.parse(
        JSON.stringify({
          ...row,
          order
        })
      )
    );
    formLabelAlign.tableData.map(item => {
      item["indNameIndex"] = item.indName;
    });
    changeIndexList.value = formLabelAlign.tableData;
    indexList.value = formLabelAlign.tableData.reduce((acc, current) => {
      // 检查 current.indLimitScore 是否为空，如果为空则跳过
      if (!current.indLimitScore) {
        return acc; // 直接返回当前的结果数组，不做任何操作
      }
      // 找到当前项的 indLimitScore 是否已经存在于结果数组中
      let found = acc.find(
        group => group[0].indLimitGroup === current.indLimitGroup
      );
      if (found) {
        // 如果找到了，添加当前项到对应的数组中
        found.push(current);
      } else {
        // 如果没有找到，创建一个新的数组并将当前项加入
        acc.push([current]);
      }
      return acc;
    }, []);
    indexList.value.map(item => {
      oldIndexList.indLimitScore.push(item[0].indLimitScore);
    });
    watchTableData();
  }
  drawer.value = true;
};
// 开关状态
const showIndicRemarkValue = computed({
  get: () => formLabelAlign.showIndicRemark === 1,
  set: value => {
    formLabelAlign.showIndicRemark = value ? 1 : 0;
  }
});
const showScoreRuleValue = computed({
  get: () => formLabelAlign.showScoreRule === 1,
  set: value => {
    formLabelAlign.showScoreRule = value ? 1 : 0;
  }
});

const showDatasourceValue = computed({
  get: () => formLabelAlign.showDatasource === 1,
  set: value => {
    formLabelAlign.showDatasource = value ? 1 : 0;
  }
});

const showTargetValueValue = computed({
  get: () => formLabelAlign.showTargetValue === 1,
  set: value => {
    formLabelAlign.showTargetValue = value ? 1 : 0;
  }
});

const showFinalValueValue = computed({
  get: () => formLabelAlign.showFinalValue === 1,
  set: value => {
    formLabelAlign.showFinalValue = value ? 1 : 0;
  }
});

const showChallengeValueValue = computed({
  get: () => formLabelAlign.showChallengeValue === 1,
  set: value => {
    formLabelAlign.showChallengeValue = value ? 1 : 0;
  }
});

const showStartValueValue = computed({
  get: () => formLabelAlign.showStartValue === 1,
  set: value => {
    formLabelAlign.showStartValue = value ? 1 : 0;
  }
});
const remarkValueValue = computed({
  get: () => formLabelAlign.showRemark === 1,
  set: value => {
    formLabelAlign.showRemark = value ? 1 : 0;
  }
});
// 分割————————————————————————————————————————————
// 新建维度
const postAddDimensionApi = async () => {
  const { code, msg } = await postAddDimension(formLabelAlign);
  if (code === 200) {
    ElMessage({
      message: "添加成功",
      type: "success"
    });
    $emit("handClick", formLabelAlign.tpId);
    drawer.value = false;
  } else {
    ElMessage({
      message: msg,
      type: "error"
    });
  }
};
// 更新维度
const postUpdateDeptApi = async () => {
  const { code, msg } = await postUpdateDept(formLabelAlign);

  if (code === 200) {
    // ElMessage({
    //   message: "更新成功",
    //   type: "success"
    // });
    // $emit("handClick", formLabelAlign.tpId);
    // drawer.value = false;
  } else {
    ElMessage({
      message: msg,
      type: "error"
    });
  }
};
const handClose = (indName, ind, indId) => {
  let newIndName = indName;
  newIndName.indLimitScore = null;
  formLabelAlign.tableData.push(newIndName);
  indexList.value[ind].splice(indId, 1);
  if (indexList.value[ind].length == 0) {
    oldIndexList.indLimitScore.splice(ind, 1);
    indexList.value.splice(ind, 1);
  }
  // 删除前面push的脏数据时遍历报错，在发送请求会过滤掉脏数据
  // if (!indexList.value[ind][0].id && indexList.value[ind].length == 1) {
  //   oldIndexList.indLimitScore.splice(ind, 1);
  //   indexList.value[ind].splice(0, 1);
  // }
};
const delteIndex = (index, item) => {
  nextTick(() => {
    indexList.value[index].map(it => {
      if (it.id) {
        it.indLimitScore = null;
        formLabelAlign.tableData.push(it);
      }
    });
    indexList.value.splice(index, 1);
    oldIndexList.indLimitScore.splice(index, 1);
  });
};
const addIndex = () => {
  nextTick(() => {
    indexList.value.push([
      {
        indNameIndex: "",
        indLimitScore: null
      }
    ]);
    oldIndexList.indLimitScore.push(1);
  });
};
const watchTableData = () => {
  const idsToDelete = new Set();
  // 通过 indexList 删除 tableData 中相同 id 的数据
  // 迭代 indexList 中的每个 id
  indexList.value.forEach(group => {
    group.forEach(item => {
      idsToDelete.add(item.id);
    });
  });
  const filteredTableData = formLabelAlign.tableData.filter(
    item => !idsToDelete.has(item.id)
  );
  formLabelAlign.tableData = filteredTableData;
};
const handChangeIndex = (ind, val) => {
  // <!--select使用交互有bug，响应式数据加载慢-- >
  // changeIndexList.value.map(item => {
  //   if (item.id == val) {
  //     nextTick(() => {
  //       indexList.value[ind].push(item);
  //       watchTableData();
  //     });
  //   }
  // });
  nextTick(() => {
    indexList.value[ind].push(val);
    watchTableData();
  });
};
const postUpdateApi = async () => {
  let codeList = [];
  let successList = [];
  for (const [index, item] of indexList.value.entries()) {
    const newIndLimitGroup = `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    for (const item1 of item) {
      if (item1.id) {
        item1.indLimitScore = oldIndexList.indLimitScore[index];
        item1.indLimitScore = Number(item1.indLimitScore);
        const { code } = await postUpdate({
          ...item1,
          indLimitGroup: item1.indLimitGroup || newIndLimitGroup
        });
        codeList.push(item1.id);
        if (code === 200) {
          successList.push(code);
        }
      }
    }
  }
  for (let item of formLabelAlign.tableData) {
    const { code } = await postUpdate({
      ...item
    });
    if (code === 200) {
      successList.push(code);
    }
  }

  if (successList.every(code => code === 200)) {
    ElMessage({
      message: "更新成功",
      type: "success"
    });
    $emit("handClick", formLabelAlign.tpId);
    drawer.value = false;
  }
};
defineExpose({
  open
});
// 输入验证方法
const validateInput = ind => {
  // 转换输入为数字
  console.log("ind", ind);
  const num = parseFloat(oldIndexList.indLimitScore[ind]);

  // 如果输入不是有效的数字，或者小于等于0，清空输入框
  if (isNaN(num) || num <= 0) {
    ElMessage.error("请输入大于0的数字,且不能为空");
    oldIndexList.indLimitScore[ind] = 1;
  }
};
</script>

<template>
  <div>
    <el-drawer
      v-model="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <template #header>
        <h4>{{ titleName }}</h4>
      </template>
      <template #default>
        <div>
          <el-form
            ref="ruleFormRef"
            label-position="top"
            label-width="auto"
            :model="formLabelAlign"
          >
            <el-form-item
              label="维度名称"
              prop="dimName"
              label-position="top"
              :rules="[
                {
                  required: true,
                  message: '请输入模板名称',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input v-model="formLabelAlign.dimName" />
            </el-form-item>
            <el-form-item label="维度权重" label-position="top">
              <el-switch v-model="dimWeight" class="mr-4" />
              <el-input
                v-model="formLabelAlign.dimWeight"
                style="max-width: 150px"
                :disabled="!dimWeight"
                oninput="value=value.replace(/\D/g,'')"
              >
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="计算方式" label-position="top">
              <el-radio-group v-model="formLabelAlign.mode">
                <el-radio :value="0" size="large">加权</el-radio>
                <el-radio :value="1" size="large">加和</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="dalongTitle == '编辑'"
              label="指标最高分限制"
              label-position="top"
            >
              <div>
                <div v-for="(int, ind) in indexList" :key="ind" class="mt-2">
                  <el-text
                    class="mx-1"
                    type="danger"
                    @click="delteIndex(ind, int)"
                  >
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-text>
                  <el-text class="mx-1">不超过</el-text>
                  <!-- <el-input v-model="int[int.length - 1].indLimitScore" size="small" style="width: 45px" /> -->
                  <el-input
                    v-model="oldIndexList.indLimitScore[ind]"
                    size="small"
                    style="width: 45px"
                    @input="validateInput(ind)"
                  />
                  <el-text class="mx-1">分</el-text>
                  <!-- select使用交互有bug，响应式数据加载慢,拿不到最新数据 -->
                  <!-- <el-select v-model="int[int.length - 1].indNameIndex" placeholder="请选择指标" style="width: 140px"
                    filterable @change="handChangeIndex(ind, $event)">
                    <el-option v-for="item in formLabelAlign.tableData" :key="item.id" :label="item.indNameIndex"
                      :value="item.id" />
                  </el-select> -->
                  <el-dropdown trigger="click" placement="bottom-start">
                    <span class="el-dropdown-link">
                      <el-input
                        v-model="int[int.length - 1].indNameIndex"
                        style="width: 140px"
                        placeholder="请选择指标"
                      />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <div
                          v-if="formLabelAlign.tableData.length > 0"
                          style="max-height: 300px"
                        >
                          <el-scrollbar>
                            <div
                              v-if="formLabelAlign.tableData.length > 0"
                              class="p-2"
                            >
                              <div
                                v-for="item in formLabelAlign.tableData"
                                :key="item.id"
                                class="w-full h-8 flex items-center justify-center text-center cursor-pointer hoverBlue p-2"
                                @click="handChangeIndex(ind, item)"
                              >
                                <!-- <el-text class="mx-1" type="info"> -->
                                {{ item.indName }}
                                <!-- </el-text> -->
                              </div>
                            </div>
                          </el-scrollbar>
                        </div>
                        <div
                          v-else
                          class="w-[150px] h-10 flex items-center justify-center"
                        >
                          <el-text class="mx-1" type="info">暂无数据</el-text>
                        </div>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <span v-for="(indName, indId) in int" :key="indId">
                    <el-tag
                      v-if="indName.indName"
                      type="info"
                      class="ml-2"
                      closable
                      @close="handClose(indName, ind, indId)"
                    >
                      {{ indName.indName }}
                    </el-tag>
                  </span>
                </div>
                <el-tag type="primary" @click="addIndex">
                  <el-icon> <Plus /> </el-icon>添加
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="指标显示字段设置" label-position="top">
              <template #default>
                <div>
                  <div>
                    <el-text type="info">指标说明</el-text>
                    <el-switch v-model="showIndicRemarkValue" class="ml-2" />
                  </div>
                  <div>
                    <el-text type="info">评价标准</el-text>
                    <el-switch v-model="showScoreRuleValue" class="ml-2" />
                  </div>
                  <div>
                    <el-text type="info">数据来源</el-text>
                    <el-switch v-model="showDatasourceValue" class="ml-2" />
                  </div>
                  <div class="ml-3">
                    <el-text type="info">目标值</el-text>
                    <el-switch v-model="showTargetValueValue" class="ml-2" />
                  </div>
                  <!-- <div class="ml-3">
                    <el-text type="info">完成值</el-text>
                    <el-switch v-model="showFinalValueValue" class="ml-2" />
                  </div> -->
                  <div class="ml-3">
                    <el-text type="info">挑战值</el-text>
                    <el-switch v-model="showChallengeValueValue" class="ml-2" />
                  </div>
                  <div class="ml-3">
                    <el-text type="info">门槛值</el-text>
                    <el-switch v-model="showStartValueValue" class="ml-2" />
                  </div>
                  <div class="ml-3">
                    <el-text type="info">备注</el-text>
                    <el-switch v-model="remarkValueValue" class="ml-2" />
                  </div>
                </div>
              </template>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<style scoped lang="scss">
.hoverBlue {
  overflow: hidden;
  font-size: 14px;
  color: #999;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hoverBlue:hover {
  color: #4285f4 !important;
  background-color: #99999912;
}
</style>
