<template>
  <div class="tags-manage">

    <div class="main-container">
      <div class="top-screen" ref="topScreenRef">
        <qu-search-area :model="screenForm" @search="restSearch" @reset="clearScreen(screenFormRef, ['districtId'])">
          <el-form-item label="所属站点" prop="districtId">
            <div class="screen-item">
              <district-screen v-model:districtId="screenForm.districtId" ref="districtScreenRef"></district-screen>
            </div>
          </el-form-item>
          <el-form-item label="标签名称" prop="labelName">
            <div class="screen-item">
              <el-input v-model="screenForm.labelName" clearable></el-input>
            </div>
          </el-form-item>
        </qu-search-area>
      </div>
      <div class="main-table">
        <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
        <qu-table :tableData="tableData" v-model:tableHeader="tableHeader" :height="tableHeight" :pageProps="pageProps"
          :rowButtons="rowButtons" @rowButtonClick="rowButtonClick" @pageChange="pageChange" @sortChange="sortChange"
          v-loading="tableLoading" v-if="isLoaded" :tableButtons="tableButtons" @buttonClick="buttonClick">
          <template #colorValue="scope">
            <span class="custom-color" :style="{ background: scope.row.colorValue }"></span>
          </template>
        </qu-table>
      </div>
      <div v-if="showEditForm">
        <el-dialog v-model="showEditForm" :title="currentRow.data.id ? '编辑标签' : '添加标签'" width="600px">
          <el-form :model="currentRow.data" :rules="editFormRules" ref="editFormRef">
            <el-form-item label="标签名称" prop="labelName">
              <div class="form-item">
                <el-input v-model="currentRow.data.labelName" placeholder="请输入标签名称" maxlength="10"></el-input>
              </div>
            </el-form-item>

            <el-form-item label="标签颜色" prop="colorValue">
              <div class="form-item">
                <el-color-picker v-model="currentRow.data.colorValue" :predefine="predefineColors" />
                <span>{{ currentRow.data.colorValue }}</span>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <div>
              <el-button @click="showEditForm = false">取消</el-button>
              <el-button @click="submit(editFormRef)" type="primary">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import { tagService } from "@/ApiService/userCenterService";
const isLoaded = ref(false);
const tableLoading = ref(false);
const editFormRef = ref();
const showEditForm = ref(false);
const editFormRules = reactive({
  labelName: [{ required: true, message: "请输入标签名称", trigger: "change" }],
  colorValue: [
    { required: true, message: "请选择标签颜色", trigger: "change" },
  ],
});
const predefineColors = ref([
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585",
  "rgba(255, 69, 0, 0.68)",
  "rgb(255, 120, 0)",
  "hsv(51, 100, 98)",
  "hsva(120, 40, 94, 0.5)",
  "hsl(181, 100%, 37%)",
  "hsla(209, 100%, 56%, 0.73)",
  "#c7158577",
]);
const districtId = computed(() => {
  return Number($route.query.districtId)
})
const topScreenRef = ref()
const tableHeight = ref(500)
const districtScreenRef = ref()
// 数据定义 end
//#region 函数定义start
const buttonClick = (button) => {
  buttonsClickFun.data[button.enName]();
};
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow.data[i] = row[i];
  }
  buttonsClickFun.data[$column.enName]();
};
const fetchData = () => {
  const { page, rows, sord, sidx } = pageProps;
  tableLoading.value = false;
  tagService
    .pageList({ page, rows, sord, sidx, ...screenForm })
    .then(
      (res) => {
        if (res.code == 0) {
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        } else {
          $message.error(res.err);
        }
        isLoaded.value = true;
        tableLoading.value = false;
      },
      () => {
        isLoaded.value = true;
        tableLoading.value = false;
      }
    );
};
const submit = (editFormRefDom) => {
  editFormRefDom.validate((res) => {
    if (res) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
        .then(() => {
          tagService
            .addOrUpdate({ ...currentRow.data, districtId: screenForm.districtId })
            .then((res) => {
              if (res.code == 0) {
                showEditForm.value = false;
                $message.success("操作成功");
                fetchData();
                $store.dispatch('fetchTags', { districtId: screenForm.districtId })
              } else {
                $message.error(res.err);
              }
            });
        });
    }
  });
};
const fetchDistricts = () => {
  districtScreenRef.value.fetchDistricts().then(res => {
    if (res && res.length != 0) {
      screenForm.districtId = res[0].id
      fetchData();
    } else {
      isLoaded.value = true;
      tableLoading.value = false;
      $message.error('未分配站点')
    }
  });
}
const {
  $route,
  $router,
  $store,
  $message,
  $messageBox,
  screenForm,
  screenFormRef,
  selectItems,
  tableData,
  tableHeader,
  tableButtons,
  currentRow,
  rowButtons,
  pageProps,
  buttonsClickFun,
  pageChange,
  sortChange,
  restSearch,
  clearScreen,
} = templateHooks(fetchData);
//#endregion 函数定义 end
// 监听路由districtId 变化时重新获取数据
watch(districtId, val => {
  if ($route.name == 'tagsManage') {
    if (val) {
      screenForm.districtId = val
      fetchData();
    } else {
      fetchDistricts()
    }

  }

})
onMounted(() => {
  screenForm.districtId = Number($route.query.districtId)
  if (screenForm.districtId) {
    districtScreenRef.value.fetchDistricts()
    fetchData();
  } else {
    nextTick(() => {
      fetchDistricts()

    })
  }
  buttonsClickFun.data = {
    add: () => {
      for (let i in currentRow.data) {
        currentRow.data[i] = "";
      }
      showEditForm.value = true;
    },
    edit: () => {
      showEditForm.value = true;
    },
    delete: () => {
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          tagService.delete({ id: currentRow.data.id }).then((res) => {
            if (res.code == 0) {
              $message.success("删除成功");
              fetchData();
              $store.dispatch('fetchTags', { districtId: screenForm.districtId })
            } else {
              $message.error(res.err);
            }
          });
        });
    },
  };

});
watch(tableButtons, val => {
  if ($route.name == 'tagsManage') {
    if (val && val.length != 0) {
      nextTick(() => {
        const windowHeight = document.body.clientHeight
        tableHeight.value = windowHeight - topScreenRef.value.clientHeight - 170
      })

    }
  }
})
// 生命周期 end
</script>
<script>
export default {
  name: "tagsManage",
};
</script>
<style scoped>
.custom-color {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 3px;
}
</style>
