<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { ElMessageBox, ElMessage, ElTable } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { getQuotaPageList } from "@/api/indexDefine";
import { postAddRelationList } from "@/api/dimension";
import { getSelectDictListtApi, select } from "@/api/select";
import { getStateData, getStateType } from "@/config/tag";
const dialogVisibleAdd = ref(false);
const $emit = defineEmits(["handClickInit"]);
const indexParams = reactive({
  params: {
    pageNumber: 1,
    pageSize: 5,
    categoryName: "",
    param: ""
  },
  tableData: [],
  total: 0,
  tableIndex: [],
  Relation: {
    dimId: "",
    indId: "",
    tpId: "",
    indName: "",
    scoreRule: "",
    targetValue: "",
    finalValue: "",
    challengeValue: "",
    startValue: "",
    datasoure: "",
    weight: "",
    scoreValue: ""
  },
  parentList: {}
});
const handleClose = () => {
  dialogVisibleAdd.value = !dialogVisibleAdd.value;
  // ElMessageBox.confirm("确认关闭弹窗吗？")
  //   .then(() => {
  //     ElMessage({
  //       message: "已关闭"
  //     });
  //   })
  //   .catch(() => {
  //     // catch error
  //   });
};
// 添加部门保存
const saveDepartment = async () => {
  const { code, msg, data } = await postAddRelationList(indexParams.tableIndex);
  if (code === 200) {
    if (data.successList.length > 0) {
      $emit("handClickInit");
      ElMessage({
        message: "导入成功",
        type: "success"
      });
    }
    if (data.failList.length > 0) {
      data.failList.map(it => {
        ElMessage({
          message: `指标${it.indName}重复导入`,
          type: "error"
        });
      });
    }
  } else {
    ElMessage.error(msg);
  }
  // indexParams.tableIndex.forEach(async item => {
  //   indexParams.Relation.indId = item.id;
  //   indexParams.Relation.indName = item.name;
  // if (code === 200) {
  //   if (data.successList.length > 0) {
  //     $emit("handClickInit");
  //     console.log("11111", indexParams.parentList);
  //     ElMessage({
  //       message: "导入成功",
  //       type: "success"
  //     });
  //   }
  //   if (data.failList.length > 0) {
  //     console.log("11111", data.failList);
  //     ElMessage({
  //       message: `指标${data.failList[0].indName}重复导入`,
  //       type: "error"
  //     });
  //   }
  // } else {
  //   ElMessage.error(msg);
  // }
  // });
  dialogVisibleAdd.value = false;
  // ElMessageBox.confirm("不保存，更新的信息将会丢失", "需要保存吗？", {
  //   type: "warning"
  // })
  //   .then(async () => {
  //   })
  //   .catch(() => {
  //     // catch error
  //   });
};
const open = row => {
  console.log("item", row);
  Object.assign(indexParams.parentList, row);
  indexParams.Relation.dimId = row.id;
  indexParams.Relation.tpId = row.tpId;
  dialogVisibleAdd.value = true;
  getQuotaPageListApi();
  getSelectDictListtApi();
};
// 选中
const selectedNums = ref(0);
const handleSelectionChange = selectedRows => {
  // this.selectedRows = selectedRows;
  indexParams.tableIndex = [];
  selectedNums.value = selectedRows.length;
  selectedRows.forEach((item, index) => {
    indexParams.tableIndex.push({
      dimId: indexParams.Relation.dimId,
      indId: item.id,
      tpId: indexParams.Relation.tpId,
      indName: item.name,
      scoreRule: "",
      targetValue: "",
      finalValue: "",
      challengeValue: "",
      startValue: "",
      datasoure: item.datasoure,
      weight: "",
      scoreValue: "",
      order: indexParams.parentList.tableData.length + index,
      importStatus: true
    });
  });
  // indexParams.tableIndex = selectedRows;
  console.log("选中的行:", indexParams.tableIndex);
};

const getQuotaPageListApi = async () => {
  const { code, data, msg } = await getQuotaPageList(indexParams.params);
  if (code == 200) {
    indexParams.tableData = data.records;
    indexParams.total = data.totalRow;
  } else {
    ElMessage.error(msg);
  }
};
const handleSizeChange = (val: number) => {
  // console.log("a4val1111", val);
  indexParams.params.pageSize = val;
  getQuotaPageListApi();
};
const handleCurrentChange = (val: number) => {
  // console.log("a4va2222222", val);
  indexParams.params.pageNumber = val;
  getQuotaPageListApi();
};
defineExpose({
  open
});
</script>

<template>
  <div>
    <el-dialog v-model="dialogVisibleAdd" title="导入指标" width="744">
      <div class="w-full flex justify-between items-center">
        <div>
          <el-text>指标分类</el-text>
          <el-select
            v-model="indexParams.params.categoryName"
            clearable
            filterable
            placeholder="请选择"
            style="width: 200px"
            class="ml-3"
            @change="getQuotaPageListApi"
          >
            <el-option
              v-for="(item, index) in select"
              :key="index"
              :label="item.dictValue"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <div>
          <el-input
            v-model="indexParams.params.param"
            :prefix-icon="Search"
            placeholder="请输入"
            @change="getQuotaPageListApi"
          />
        </div>
      </div>
      <el-table
        :data="indexParams.tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="指标名称">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column prop="categoryName" label="指标分类" width="100" />
        <el-table-column
          property="statue"
          label="状态"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag :type="getStateType(scope.row.statue)">
              {{ getStateData(scope.row.statue) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column property="source" label="数据来源" width="120" />
      </el-table>
      <div class="w-full flex justify-between items-center">
        <div class="ml-10 mt-5">
          <el-text>共{{ indexParams.total }}项数据</el-text>
        </div>
        <div class="mr-10">
          <el-pagination
            v-model:current-page="indexParams.params.pageNumber"
            v-model:page-size="indexParams.params.pageSize"
            size="small"
            background
            layout="prev, pager, next"
            :total="indexParams.total"
            class="mt-4"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer w-full flex justify-between mt-4">
          <div>
            <el-text>已选择</el-text>
            <el-text type="primary">
              {{ selectedNums }}
            </el-text>
            <el-text>项</el-text>
          </div>

          <div>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="saveDepartment"> 确认 </el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
