<script lang="ts" setup>
import { getAllfieldList, getfieldList, savefield } from "@/api/home/filter";
import { ReportInfoConfig } from "@/config/workorder";
import { useUser } from "@/store/modules/user";
import { defineEmits, defineProps, onMounted, ref } from "vue";

const props = defineProps({
  reviewType: {
    type: Number,
    default: () => 3,
    require: true,
  },
});
onMounted(async () => {
  const userStore = useUser();
  const userInfo = userStore.getUserInfo;
  let res;
  res = await getAllfieldList(props.reviewType); //所有筛选项目
  const allList = res.data;
  res = await getfieldList(props.reviewType, userInfo.id); //当前用户选择的项目
  const useList = res.data;
  /**
   * name 标题
   * id 键值
   * fix 是否默认
   * checked 是否选中
   */
  const userFieldFixed = useList.userFieldFixed?.split(",");
  const userFieldUnFixed = useList.userFieldUnFixed?.split(",");
  allList.map((v) => {
    let item = {
      name: v.fieldDesc,
      id: v.name,
      fix: v.isrequired == 2,
      checked:
        v.isrequired == 2 ||
        Boolean(userFieldFixed?.find(v2=>v2==v.name)) ||
        Boolean(userFieldUnFixed?.find(v2=>v2==v.name))
    };
    offList.value.push(item);
  });
});

const offList = ref<any[]>([]);
function generatList() {
  const keys = Object.keys(ReportInfoConfig);
  const hideList: object[] = [];
  for (const key of keys) {
    const name = ReportInfoConfig[key]?.label;
    const isDefault = ReportInfoConfig[key]?.isDefault;

    // 系统配置为Y且不是默认配置
    if (!isDefault) {
      hideList.push({
        id: key,
        name: name || "未配置",
        fix: isDefault,
        checked: ReportInfoConfig[key].isDefault,
      });
    }
  }

  const fixedList = generateDefaultList();

  hideList.unshift(...fixedList);

  offList.value = hideList;
  return { hideList };
}

function generateDefaultList() {
  return Object.keys(ReportInfoConfig).reduce((acc, key) => {
    const { label, isDefault } = ReportInfoConfig[key];

    if (isDefault) {
      const config = {
        id: key,
        name: label || "未配置",
        fix: true,
        checked: true,
      };
      return [...acc, config];
    } else {
      return acc;
    }
  }, []);
}

const show = ref(false);
const checkAll = ref(false);

function showModal() {
  show.value = true;
}

function closeModal() {
  show.value = false;
}
const emit = defineEmits(["onOk"]);

async function handleSumbit(e: MouseEvent) {
  const userStore = useUser();
  const userInfo = userStore.getUserInfo;
  let userField = "";
  offList.value.map((v) => {
    if (v.checked) {
      userField += `${v.id},`;
    }
  });
  userField = userField.slice(0, userField.length - 1);
  savefield(props.reviewType, userInfo.id, userField);
  e.preventDefault();
  closeModal();
  emit("onOk");
}

defineExpose({
  showModal,
});

// generatList();

const selectIds = ref<string[]>([]);

function onCheckAllChange(value) {
  const ids: string[] = [];

  for (const item of offList.value) {
    if (!item.fix) {
      item.checked = value;
      ids.push(item.id);
    }
  }

  selectIds.value = value ? ids : [];
}

function onCheckChange(checked: any, item: any) {
  const index = selectIds.value.indexOf(item.id);

  item.checked = checked;

  if (index === -1 && checked) selectIds.value.push(item.id);
  else selectIds.value.splice(index, 1);
}
</script>

<template>
  <n-modal v-model:show="show" transform-origin="center">
    <n-card
      class="cardstyle"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
      <div class="wrapper">
        <span class="wrapper-title">自定义填报信息</span>
        <n-grid cols="4" class="mt-4 proCard" responsive="screen" :x-gap="24">
          <n-grid-item span="4">
            <NCard
              title=""
              class="dragcardStyle"
              :segmented="{ content: true, footer: true }"
              size="small"
              :bordered="false"
            >
              <div>
                <div class="draggable-ul">
                  <div class="draggable-li" style="background: #f8f8f8">
                    <n-checkbox
                      v-model:checked="checkAll"
                      label="全部"
                      @update:checked="onCheckAllChange"
                    />
                  </div>
                  <div class="content">
                    <div
                      v-for="item in offList"
                      :key="item.id"
                      style="width: 170px"
                      :class="{ 'disable-check': item.fix }"
                      class="draggable-li"
                    >
                      <n-checkbox
                        v-model:checked="item.checked"
                        :label="item.name"
                        :disabled="item.fix"
                        @update:checked="onCheckChange($event, item)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </NCard>
          </n-grid-item>
        </n-grid>
      </div>
      <template #footer>
        <div class="wrapper-footer">
          <n-button type="info" @click="handleSumbit"> 确认 </n-button>
          <n-button secondary style="margin-left: 15px" @click="closeModal">
            取消
          </n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<style lang="less" scoped>
.wrapper {
  display: flex;
  flex-direction: column;

  &-title {
    font-weight: bold;
    font-size: 16px;
  }

  &-bar {
    background-color: #e8e8e8;
    width: 100%;
    margin-top: 20px;
  }

  &-footer {
    display: flex;
    justify-content: flex-end;
  }

  &-info {
    font-weight: bold;
    position: relative;

    &:before {
      background-color: #1980ff;
      content: "";
      width: 5px;
      border-radius: 2px;
      top: 0;
      bottom: 0;
      position: absolute;
    }
  }
}

.dragcardStyle {
  --n-padding-bottom: 0px !important;
  --n-padding-left: 0px !important;
}

.cardstyle {
  width: 820px;
  --n-padding-bottom: 20px;
  --n-padding-left: 24px;
}

.textbtnStyle {
  cursor: pointer;
  color: #1980ff;
}

.draggable-ul {
  width: 100%;
  overflow: hidden;
  border: 1px solid #cad2dd;
  border-radius: 2px;
  display: block;

  .content {
    display: flex;
    flex-wrap: wrap;
  }

  .draggable-li {
    padding: 10px 16px;
    color: #333;
  }

  .draggable-item {
    padding: 10px 16px;
    color: #333;
    display: flex;
    align-items: center;
  }

  .disable-check {
    color: gainsboro;
  }
}

::v-deep(
    .n-card.n-card--content-segmented > .n-card__content:not(:first-child)
  ) {
  border: 0px;
}

::v-deep(.n-card > .n-card-header) {
  --n-padding-top: 0px;
  --n-padding-bottom: 12px;
}
</style>
