<script setup lang="ts">
defineOptions({
  name: "evaluateNewAdd"
});
import { ref, reactive, onMounted } from "vue";
import one from "@/assets/svg/2.svg";
import two from "@/assets/svg/1.svg";
import one1 from "@/assets/svg/2-2.svg";
import two2 from "@/assets/svg/1-1.svg";
import { useRouter, useRoute } from "vue-router";
import { Edit } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { postAddRelationList, postUpdateDept } from "@/api/dimension";
import { useAppStoreHook } from "@/store/modules/app";
import { addQuota } from "@/api/indexDefine";
import { postUpdateTemplateIn, deleteIndicator } from "@/api/templateInfo";
import {
  postAddDimension,
  getDimensionRemove,
  getQuotaByDimensionId
} from "@/api/dimension";
import editMould from "./editMould.vue";
import {
  VueDraggable,
  useDraggable,
  type DraggableEvent,
  type UseDraggableReturn
} from "vue-draggable-plus";
import { delQuota, postAddDisposableQuota } from "@/api/indexDefine";
import settingIndexDrawer from "./settingIndexDrawer.vue";
import {
  postAddTemplate,
  getInfo,
  getListBy,
  postUpdate
} from "@/api/templateInfo";
import importIndex from "./importIndex.vue";
import { formulaParamsChange } from "@/utils/business";

const router = useRouter();
const route = useRoute();
const formRef = ref();
const active = ref(0);
const editDrawer = ref();
const editDrawerShow = ref(false);
const titleShow = ref(false);

// 序号
const order = ref();
// 指标设置
const settingIndexDrawerRef = ref();
const settingIndexDrawerShow = ref(false);
// 导入指标
const importIndexRef = ref();
const importIndexShow = ref(false);
const handleSelect = index => {
  // console.log(index);
  active.value = index;
};
const tepName = ref();
const tepNameForm = reactive({
  tpName: "",
  id: "",
  isScoreConverse: 1
});
onMounted(() => {
  if (route.query.tpName && route.query.id) {
    tepNameForm.tpName = route.query.tpName;
    tepNameForm.id = route.query.id;
    console.log("route.query", route.query);
    tepNameForm.isScoreConverse = Number(route.query.isScoreConverse);
  }
});
const tableData = ref([]);

// 新建模板
const postAddTemplateApi = async () => {
  const res = await postAddTemplate({ ...tepNameForm });
  Object.assign(tepNameForm, {
    tpName: "",
    id: ""
  });
  if (res.code === 200) {
    ElMessage({
      message: "创建成功",
      type: "success"
    });
    tepNameForm.tpName = res.data.tpName;
    tepNameForm.id = res.data.id;
    tepNameForm.isScoreConverse = res.data.isScoreConverse;
    titleShow.value = true;
  } else {
    ElMessage.error(res.msg);
  }
};
// 考核维度卡片
const eaxmCard = ref([]);
// 获取维度
const getListByApi = async (id?: number | string) => {
  eaxmCard.value = [];
  const obj = {
    tpId: tepNameForm.id,
    id
  };
  const { code, data, msg } = await getListBy(obj);
  if (code === 200) {
    titleShow.value = true;
    eaxmCard.value = data;
    eaxmCard.value.forEach(item => {
      initializeTableData(item);
    });
  } else {
    ElMessage.error(msg);
  }
};
const getAddListByApi = async id => {
  const obj = {
    tpId: id
  };
  const { code, data, msg } = await getListBy(obj);
  if (code === 200) {
    eaxmCard.value = data;
    eaxmCard.value.forEach(item => {
      initializeTableData(item);
    });
  } else {
    ElMessage.error(msg);
  }
};
// 获取指标信息
const paramsIndex = reactive({
  id: "",
  tpId: "",
  dimId: ""
});
const getQuotaByDimensionIdApi = async id => {
  paramsIndex.dimId = id;
  const { code, data, msg } = await getQuotaByDimensionId(paramsIndex);
  if (code === 200) {
    return data;
  } else {
    ElMessage.error(msg);
    return [];
  }
};
const initializeTableData = async item => {
  item.tableData = await getQuotaByDimensionIdApi(item.id);
};
const amountTo = itemList => {
  let num = 0;
  if (itemList) {
    itemList.forEach(item => {
      num = num + item.weight;
    });
    return num;
  }
};
const addDimension = reactive({
  list: [
    {
      id: "",
      dimName: "",
      dimWeight: "",
      mode: ""
    }
  ],
  dimName: "",
  dimWeight: "",
  mode: "",
  showIndicRemark: "",
  showScoreRule: "",
  showDatasource: "",
  showTargetValue: "",
  showFinalValue: "",
  showChallengeValue: "",
  showStartValue: "",
  remark: ""
});
// 创建考核维度
const createAdd = () => {
  order.value = eaxmCard.value.length + 1;
  editDrawer.value.open(tepNameForm, "新建", order.value);
};
const backChange = () => {
  useAppStoreHook().toggleSideBar(true, "打开");
  router.back();
};
// 更新模板
const postUpdateTemplateInApi = async () => {
  const { code, msg } = await postUpdateTemplateIn({
    tpName: tepNameForm.tpName,
    id: tepNameForm.id,
    isScoreConverse: tepNameForm.isScoreConverse
  });
  if (code == 200) {
    titleShow.value = true;
  } else {
    ElMessage.error(msg);
  }
};
// 保存
const save = () => {
  if (titleShow.value) {
    router.back();
    useAppStoreHook().toggleSideBar(true, "打开");
  } else {
    formRef.value.validate(valid => {
      if (valid) {
        if (tepNameForm.id) {
          getAddListByApi(tepNameForm.id);
          postUpdateTemplateInApi();
          if (router.query) {
          }
        } else {
          postAddTemplateApi();
        }
      }
    });
  }
};
const deleteRow = row => {
  console.log(row);
  ElMessageBox.confirm(
    "指标删除后不可恢复，请谨慎操作！",
    "确定删除该指标吗？",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      const { code, msg } = await deleteIndicator(row.id);
      if (code === 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        // initializeTableData(row.dimId);
        getListByApi();
      } else {
        ElMessage.error(msg);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消"
      });
    });
};
// 编辑
const editPen = (item, order) => {
  editDrawer.value.open(item, "编辑", order);
};
// 删除考核维度
const deletePen = item => {
  ElMessageBox.confirm(
    "该维度删除后不可恢复，请谨慎操作！",
    "确定删除考核维度",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      // eaxmCard.value.splice(index, 1);
      const { code, msg } = await getDimensionRemove(item.id);
      if (code === 200) {
        getListByApi();
        ElMessage({
          type: "success",
          message: "删除成功"
        });
      } else {
        ElMessage.error(msg);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消"
      });
    });
};
const settingIndex = row => {
  settingIndexDrawerRef.value.open(row);
};
const importIndexDialog = row => {
  importIndexRef.value.open(row);
};
const importIndexOne = async row => {
  let formula = JSON.stringify({
    noConditionFormula: ""
  });
  console.log(row, "获取的数据");
  const { code, data, msg } = await postAddDisposableQuota({ name: "" });
  if (code == 200) {
    const res = await postAddRelationList([
      {
        dimId: row.id,
        indId: data.id,
        tpId: row.tpId,
        formula,
        scoreStandard: 0,
        order: row.tableData.length + 1
      }
    ]);
    if (res.code === 200) {
      initializeTableData(row);
      ElMessage({
        type: "success",
        message: "添加成功"
      });
    } else {
      ElMessage.error(res.msg);
    }
  } else {
    ElMessage.error(msg);
  }
};
// 拖拽
const elDraggable = ref();
const elDraggableTableData = ref();
// 更新
const postUpdateDeptApi = async (id, dimName, order) => {
  await postUpdateDept({
    id,
    dimName,
    order,
    tpId: tepNameForm.id
  });
};
const onEnd = (e: DraggableEvent) => {
  eaxmCard.value.map((item, index) => {
    postUpdateDeptApi(item.id, item.dimName, index + 1);
  });
};
const onStart = (e: DraggableEvent) => {};

const onUpdate = (e: DraggableEvent) => {};

const postUpdateApi = async row => {
  // indexOf.indName = indexOf.name
  const params = { ...row };

  const { code, msg } = await postUpdate(params);
  if (code == 200) {
    // getListByApi();
    ElMessage.success("编辑成功");
  } else {
    ElMessage.error(msg);
  }
};
const indexOf = reactive({
  id: "",
  tpId: "",
  dimId: "",
  indId: "",
  valueInput: 0,
  designatedPersonnel: "",
  scoreStandard: 0,
  remark: "",
  createUser: "",
  createTime: 0,
  updateUser: "",
  updateTime: 0,
  isDelete: 0,
  scoreRule: "",
  targetValue: 0,
  finalValue: 0,
  challengeValue: 0,
  startValue: 0,
  datasoure: "",
  weight: 0,
  scoreValue: 0,
  formula: "",
  formulaType: 0,
  formulaParams: [],
  order: 0,
  indName: ""
});
const editConfig = ref<any>({
  trigger: "click",
  mode: "cell",
  beforeEditMethod({ row }) {
    if (row.stshowDatasourceate == "BI") {
      return false;
    }
    return true;
  }
});
const tableVxeRef = ref();
const editClosedEvent = ({ row, column }) => {
  const $table = tableVxeRef.value;
  if ($table) {
    Object.assign(indexOf, row);
    console.log("indexOf", indexOf, row);
    postUpdateApi(row);
  }
};
// 列表行拖拽
const columnConfig = reactive({
  useKey: true
});
const resultEvent = () => {
  const $table = tableRef.value;
  if ($table) {
    const { visibleData } = $table.getTableData();
    console.log(visibleData);
  }
};
const titleShowClick = () => {
  titleShow.value = true;
  if (route.query.id) {
    getListByApi();
  }
};
</script>

<template>
  <div class="w-[100%]">
    <!-- 导入指标 -->
    <importIndex
      ref="importIndexRef"
      v-model="importIndexShow"
      @handClickInit="getListByApi"
    />
    <!-- 指标设置 -->
    <settingIndexDrawer
      ref="settingIndexDrawerRef"
      v-model:drawerValue="settingIndexDrawerShow"
      @refresh="getListByApi"
    />
    <!-- 新增、编辑模块 -->
    <editMould
      ref="editDrawer"
      v-model:drawerValue="editDrawerShow"
      @handClick="getAddListByApi"
    />
    <div class="w-[100%] flex justify-evenly">
      <div class="left-box">
        <el-text class="cursor-pointer" @click="backChange"
          ><el-icon> <ArrowLeft /> </el-icon>返回</el-text
        >
      </div>
      <div class="center-box">
        <div
          style="max-width: 220px"
          class="m-auto flex justify-between items-center"
        >
          <div
            :class="{ 'step-success': !titleShow, 'step-error': titleShow }"
            class="w-[100px] flex justify-center items-center"
            @click="titleShow = false"
          >
            <one v-if="titleShow" />
            <two2 v-else />基础信息
          </div>
          <div
            :class="{ 'step-success': titleShow, 'step-error': !titleShow }"
            class="w-[100px] flex justify-center items-center"
          >
            <two v-if="titleShow" />
            <one1 v-else />考核指标
          </div>
        </div>
      </div>
      <div class="right-box">
        <el-button type="primary" class="mr-2" @click="save()">保存</el-button>
      </div>
    </div>
    <div class="mt-2">
      <div v-if="!titleShow" class="w-[40%] m-auto mt-10">
        <el-form
          ref="formRef"
          :model="tepNameForm"
          label-width="auto"
          style="max-width: 600px"
        >
          <el-form-item
            prop="tpName"
            label="模板名称"
            :rules="[
              {
                required: true,
                message: '请输入模板名称',
                trigger: 'blur'
              }
            ]"
          >
            <el-input
              v-model="tepNameForm.tpName"
              placeholder="最多输入100字"
            />
          </el-form-item>
          <!-- <el-form-item
            prop="isScoreConverse"
            label="是否支持得分换算"
            :rules="[
              {
                required: true,
                message: '是否支持得分换算',
                trigger: 'blur'
              }
            ]"
          >
            <el-radio-group v-model="tepNameForm.isScoreConverse">
              <el-radio :value="1" size="large">是</el-radio>
              <el-radio :value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
      </div>
      <div v-else class="w-[90%] m-auto mt-4">
        <div class="relative h-10">
          <el-button class="float-right" type="primary" plain @click="createAdd"
            >创建考核维度</el-button
          >
        </div>
        <VueDraggable
          ref="elDraggable"
          v-model="eaxmCard"
          :animation="150"
          ghostClass="ghost"
          class="flex flex-col gap-2 p-4 w-300px h-300px m-auto bg-gray-500/5 rounded"
          @start="onStart"
          @update="onUpdate"
          @end="onEnd"
        >
          <el-card v-for="(item, index) in eaxmCard" :key="index" class="mb-3">
            <template #header>
              <div class="card-header">
                <span>{{ item.dimName }}（{{ item.dimWeight }}%）</span>
                <div class="float-right mr-7">
                  <el-icon class="mr-3" @click="editPen(item, index + 1)">
                    <EditPen />
                  </el-icon>
                  <el-icon @click="deletePen(item)">
                    <Delete class="text-red-500" />
                  </el-icon>
                </div>
              </div>
            </template>

            <!-- <el-table :data="item.tableData" style="width: 100%" max-height="250">
              <el-table-column ref="elDraggableTableData" fixed prop="name" label="指标名称">
                <template #default="{ row }">
                  <div>{{ row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column v-if="item.showIndicRemark" prop="remark" label="指标说明" width="120" />
              <el-table-column v-if="item.showScoreRule" prop="scoreRule" label="评价标准" width="300" />
              <el-table-column v-if="item.showDatasource" prop="stshowDatasourceate" label="数据来源" width="120" />
              <el-table-column v-if="item.mode" prop="weight" label="权重" width="120" />
              <el-table-column v-if="item.showTargetValue" prop="targetValue" label="目标值" width="120" />
              <el-table-column v-if="item.showFinalValue" prop="finalValue" label="完成值" width="120" />
              <el-table-column v-if="item.showChallengeValue" prop="challengeValue" label="挑战值" width="120" />
              <el-table-column v-if="item.showStartValue" prop="startValue" label="门槛值" width="120" />
              <el-table-column fixed="right" label="操作">
                <template #default="{ row }">
                  <el-icon class="mr-3" @click="settingIndex(row)">
                    <Setting />
                  </el-icon>
                  <el-icon @click="deleteRow(row)">
                    <Delete class="text-red-500" />
                  </el-icon>
                </template>
              </el-table-column>
            </el-table> -->
            <vxe-table
              ref="tableVxeRef"
              border
              show-overflow
              :edit-config="editConfig"
              :data="item.tableData"
              :column-config="columnConfig"
              @edit-closed="editClosedEvent"
            >
              <vxe-column
                field="indName"
                fixed
                drag-sort
                title="指标名称"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                v-if="item.showIndicRemark"
                field="indicRemark"
                title="指标说明"
                :edit-render="{ name: 'input' }"
                drag-sort
              />
              <vxe-column
                v-if="item.showScoreRule"
                field="scoreRule"
                title="评价标准"
                :edit-render="{ name: 'input' }"
                width="300"
              />
              <vxe-column
                v-if="item.showDatasource"
                field="stshowDatasourceate"
                title="数据来源"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                v-if="item.mode == 0 || item.dimWeight != 0"
                field="weight"
                title="权重"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                field="scoreValue"
                title="分值"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                v-if="item.showTargetValue"
                field="targetValue"
                title="目标值"
                :edit-render="{ name: 'input' }"
              />
              <!-- <vxe-column
                v-if="item.showFinalValue"
                field="finalValue"
                title="完成值"
                :edit-render="{ name: 'input' }"
              /> -->
              <vxe-column
                v-if="item.showChallengeValue"
                field="challengeValue"
                title="挑战值"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                v-if="item.showStartValue"
                field="startValue"
                title="门槛值"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column
                v-if="item.showRemark"
                field="remark"
                title="备注"
                :edit-render="{ name: 'input' }"
              />
              <vxe-column field="age" fixed="right" title="操作">
                <template #default="{ row }">
                  <el-icon class="mr-3" @click="settingIndex(row)">
                    <Setting />
                  </el-icon>
                  <el-icon @click="deleteRow(row)">
                    <Delete class="text-red-500" />
                  </el-icon>
                </template>
              </vxe-column>
            </vxe-table>
            <template #footer>
              <el-button
                type="primary"
                link
                class="mr-4"
                @click="importIndexOne(item)"
              >
                添加指标
              </el-button>
              <el-button type="primary" link @click="importIndexDialog(item)">
                导入指标
              </el-button>
              <span class="float-right num"
                >指标权重合计:{{ amountTo(item.tableData) }}</span
              >
            </template>
          </el-card>
        </VueDraggable>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.left-box {
  display: flex;
  flex: 0 0 5%;
  align-items: center;
  margin: auto;
  text-align: center;
  // justify-content: center;
}

.center-box {
  flex: 0 0 70%;
}

.right-box {
  display: flex;
  flex: 0 0 5%;
  align-items: center;
  justify-content: center;
  margin: auto;
}

.step-success {
  height: 24px;
  padding-bottom: 5px;
  font-size: 16px;
  // font-family: PingFangSC-SNaNpxibold;
  font-weight: 600;
  line-height: 24px;
  color: black;
  color: #000000e6;
  border-bottom: 2px solid #022bbd;
}

.step-error {
  height: 24px;
  padding-bottom: 5px;
  font-size: 16px;
  // font-family: PingFangSC-SNaNpxibold;
  font-weight: 600;
  line-height: 24px;
  color: #0006;
  letter-spacing: 0;
}

.num {
  font-size: 14px;
  // font-family: PingFangSC-Regular;
  font-weight: 400;
  line-height: 22px;
  color: #0009;
  letter-spacing: 0;
}
</style>
