<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 {
  postAddDimension,
  getDimensionRemove,
  getQuotaByDimensionId
} from "@/api/dimension";
import editMould from "./editMould.vue";
import {
  VueDraggable,
  useDraggable,
  type DraggableEvent,
  type UseDraggableReturn
} from "vue-draggable-plus";
import { delQuota } from "@/api/indexDefine";
import settingIndexDrawer from "./settingIndexDrawer.vue";
import {
  postAddTemplate,
  getInfo,
  getListBy,
  postUpdate
} from "@/api/templateInfo";
import importIndex from "./importIndex.vue";
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();
onMounted(() => {
  if (route.query.tpName) {
    tepNameForm.tpName = route.query.tpName;
    tepNameForm.id = route.query.id;
  }
});
const tableData = ref([]);
const tepNameForm = reactive({
  tpName: "",
  id: ""
});
// 新建模板
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;
    titleShow.value = true;
  } else {
    ElMessage.error(res.msg);
  }
};
// 考核维度卡片
const eaxmCard = ref([]);
// 获取维度
const getListByApi = async () => {
  console.log(tepNameForm.id);
  const { code, data, msg } = await getListBy(tepNameForm.id);
  Object.assign(tepNameForm, {
    tpName: "",
    id: ""
  });
  if (code === 200) {
    titleShow.value = true;
    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 save = () => {
  if (titleShow.value) {
    router.back();
    useAppStoreHook().toggleSideBar(true, "打开");
  } else {
    formRef.value.validate(valid => {
      if (valid) {
        if (tepNameForm.id) {
          getListByApi();
        } else {
          postAddTemplateApi();
        }
      }
    });
  }
};
const deleteRow = row => {
  console.log(row);
  ElMessageBox.confirm(
    "指标删除后不可恢复，请谨慎操作！",
    "确定删除该指标吗？",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      const { code, msg } = await delQuota(row.id);
      if (code === 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        initializeTableData(row.dimId);
      } else {
        ElMessage.error(msg);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "用户取消"
      });
    });
};
// 编辑
const editPen = (item, order) => {
  editDrawer.value.open(item, "编辑", order);
};
// 删除考核维度
const deletePen = index => {
  ElMessageBox.confirm(
    "该维度删除后不可恢复，请谨慎操作！",
    "确定删除考核维度",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      // eaxmCard.value.splice(index, 1);
      const { code, msg } = await getDimensionRemove(index);
      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 => {
  // console.log("row", row);
  const res = await postAddRelationList([
    {
      dimId: row.id,
      indId: row.tpId,
      tpId: ""
    }
  ]);
  if (res.code === 200) {
    initializeTableData(row);
    ElMessage({
      type: "success",
      message: "添加成功"
    });
  } else {
    ElMessage.error(res.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 (dimId, indId, order) => {
  await postUpdate({
    tpId: tepNameForm.id,
    dimId,
    indId,
    order
  });
};
// const { start } = useDraggable(elDraggableTableData, eaxmCard.tableData, {
//   animation: 150,
//   ghostClass: "ghost",
//   onStart() {
//     // console.log("start");
//   },
//   onUpdate(item, index) {
//     console.log("update", item);
//     console.log("index", index);
//   }
// });
// const onEndTbl = (item: any, id: any) => {
//   console.log(item, id);
//   item.map((item, index) => {
//     postUpdateApi(id, item.id, index + 1);
//   });
// };
</script>

<template>
  <div class="w-[100%]">
    <!-- 导入指标 -->
    <importIndex
      ref="importIndexRef"
      v-model="importIndexShow"
      @handClickInit="initializeTableData"
    />
    <!-- 指标设置 -->
    <settingIndexDrawer
      ref="settingIndexDrawerRef"
      v-model:drawerValue="settingIndexDrawerShow"
    />
    <!-- 新增、编辑模块 -->
    <editMould
      ref="editDrawer"
      v-model:drawerValue="editDrawerShow"
      @handClick="getListByApi"
    />
    <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"
          >
            <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>
      </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.id)"
                    ><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>
            <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>
