<template>
  <div>
    <el-form
      :model="searchForm"
      label-width="80px"
      @submit.prevent="fnResetPaginationTransfer"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="名称" prop="KEYWORDS">
            <el-input
              v-model="searchForm.KEYWORDS"
              placeholder="请输入关键字"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="规程属性" prop="CATEGORY_LIST">
            <layout-three-institutional-libraries
              ref="regulationsRef"
              v-model="searchForm.CATEGORY_LIST"
              type="regulations"
              collapse-tags
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="类型" prop="TYPES">
            <layout-three-institutional-libraries
              ref="typeRef"
              v-model="searchForm.TYPES"
              type="type"
              collapse-tags
              :path-name="pathName"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="国民经济行业类型"
            prop="SPECIFICATION_TYPES"
            label-width="130px"
          >
            <layout-three-institutional-libraries
              ref="industryRef"
              v-model="searchForm.SPECIFICATION_TYPES"
              type="industry"
              collapse-tags
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="标签" prop="labels">
            <layout-three-institutional-libraries
              ref="labelRef"
              v-model="searchForm.labels"
              type="label"
              collapse-tags
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="企业" prop="CORPINFO_ID">
            <el-select
              v-model="searchForm.CORPINFO_ID"
              :remote-method="fnRemoteMethod"
              :loading="selectLoading"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.CORPINFO_ID"
                :label="item.CORP_NAME"
                :value="item.CORPINFO_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label-width="10px">
            <el-button type="primary" native-type="submit">搜索</el-button>
            <el-button native-type="reset" @click="fnResetPaginationTransfer">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <layout-table
      v-model:pagination="pagination"
      :data="list"
      @get-data="fnGetDataTransfer"
    >
      <el-table-column label="序号" width="70">
        <template #default="{ $index }">
          {{ serialNumber(pagination, $index) }}
        </template>
      </el-table-column>
      <el-table-column prop="REMARKS" :label="labelName" />
      <el-table-column label="类型">
        <template #default="{ row }">
          {{
            row.TYPES.map((item) => item.CATEGORY_NAME)
              .filter(Boolean)
              .join("、")
          }}
        </template>
      </el-table-column>
      <el-table-column label="标签">
        <template #default="{ row }">
          {{
            row.labels
              .map((item) => item.NAME)
              .filter(Boolean)
              .join("、")
          }}
        </template>
      </el-table-column>
      <el-table-column label="国民经济行业类型">
        <template #default="{ row }">
          <span v-if="row.SPECIFICATION_TYPES?.length > 0">
            {{
              row.SPECIFICATION_TYPES.map((item) => item.CATEGORY_NAME)
                .filter(Boolean)
                .join("、")
            }}
          </span>
          <span v-else>通用</span>
        </template>
      </el-table-column>
      <el-table-column prop="UPLOAD_TIME" label="上传时间" width="150px" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            v-if="tabName === 'platform_resource_library'"
            type="primary"
            text
            link
            @click="fnJoinLocal(row.BUS_TEXT_LIBRARY_ID)"
          >
            加入本地
          </el-button>
          <el-button
            type="primary"
            text
            link
            @click="fnView(row.BUS_TEXT_LIBRARY_ID)"
          >
            查看
          </el-button>
          <template v-if="tabName === 'self_administered'">
            <el-button
              v-if="buttonJurisdiction.edit"
              type="primary"
              text
              link
              @click="fnAddOrEdit(row.BUS_TEXT_LIBRARY_ID, 'edit')"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              text
              link
              @click="useDownloadFile(row.PATH)"
            >
              导出
            </el-button>
            <el-button
              v-if="buttonJurisdiction.del"
              type="primary"
              text
              link
              @click="fnDelete(row.BUS_TEXT_LIBRARY_ID)"
            >
              删除
            </el-button>
          </template>
        </template>
      </el-table-column>
      <template #button>
        <el-button
          v-if="buttonJurisdiction.add && tabName === 'self_administered'"
          type="primary"
          @click="fnAddOrEdit('', 'add')"
        >
          新增
        </el-button>
      </template>
    </layout-table>
    <add
      v-model:visible="data.addOrEditDialog.visible"
      v-model:form="data.addOrEditDialog.form"
      :type="data.addOrEditDialog.type"
      :label-name="labelName"
      :association="ASSOCIATION[pathName]"
      :path-name="pathName"
      @get-data="fnResetPaginationTransfer"
    />
    <view-info
      v-model:visible="data.viewDialog.visible"
      :info="data.viewDialog.info"
      :label-name="labelName"
    />
  </div>
</template>

<script setup>
import { addingPrefixToFile, serialNumber } from "@/assets/js/utils.js";
import useListData from "@/assets/js/useListData.js";
import {
  getThreeInstitutionalLibrariesList,
  getThreeInstitutionalLibrariesView,
  getThreeInstitutionalLibrariesViewText,
  setThreeInstitutionalLibrariesDelete,
  setThreeInstitutionalLibrariesJoinLocal,
} from "@/request/three_institutional_libraries.js";
import LayoutThreeInstitutionalLibraries from "@/components/three_institutional_libraries/index.vue";
import { nextTick, reactive, ref } from "vue";
import { getEnterpriseList } from "@/request/enterprise_management.js";
import { debounce, throttle } from "throttle-debounce";
import useButtonJurisdiction from "@/assets/js/useButtonJurisdiction.js";
import { ElMessage, ElMessageBox } from "element-plus";
import useDownloadFile from "@/assets/js/useDownloadFile.js";
import Add from "./add.vue";
import ViewInfo from "./view.vue";

const props = defineProps({
  tabName: {
    type: String,
    required: true,
    default: "",
  },
  pathName: {
    type: String,
    required: true,
    default: "",
  },
  labelName: {
    type: String,
    required: true,
    default: "",
  },
});
const regulationsRef = ref(null);
const typeRef = ref(null);
const industryRef = ref(null);
const labelRef = ref(null);
const data = reactive({
  addOrEditDialog: {
    visible: false,
    type: "",
    form: {
      REMARKS: "",
      TYPES: [],
      file: [],
      TEXT_INFO: "",
      labels: [],
    },
  },
  viewDialog: {
    visible: false,
    info: {},
  },
});
const ASSOCIATION = {
  safety_production_responsibility_system: "2",
  safety_production_management_system: "1",
  safety_operating_procedures: "0",
};
const fnGetOtherParams = () => {
  const otherParams = { ASSOCIATION: ASSOCIATION[props.pathName] };
  if (props.tabName === "self_administered") {
    otherParams.ENTERPRISE_SIDE = "0";
  } else if (props.tabName === "platform_resource_library") {
    otherParams.CORPINFO_ID = "0";
  }
  return otherParams;
};
const { list, pagination, searchForm, fnGetData, fnResetPagination } =
  useListData(getThreeInstitutionalLibrariesList, {
    otherParams: fnGetOtherParams(),
  });
const buttonJurisdiction = await useButtonJurisdiction("textlibrary");
const fnGetCheckedNodes = async () => {
  await nextTick();
  const CATEGORY_LIST = await regulationsRef.value.getCheckedNodes();
  const TYPES = await typeRef.value.getCheckedNodes();
  const SPECIFICATION_TYPES = await industryRef.value.getCheckedNodes();
  const labels = await labelRef.value.getCheckedNodes();
  return {
    CATEGORY_LIST: JSON.stringify(CATEGORY_LIST),
    TYPES: JSON.stringify(TYPES),
    SPECIFICATION_TYPES: JSON.stringify(SPECIFICATION_TYPES),
    labels: JSON.stringify(labels),
  };
};
const fnGetDataTransfer = async () => {
  fnGetData({ ...(await fnGetCheckedNodes()) });
};
const fnResetPaginationTransfer = async () => {
  fnResetPagination({ ...(await fnGetCheckedNodes()) });
};
const selectLoading = ref(false);
const enterpriseList = ref([]);
const fnRemoteMethod = throttle(500, async (query) => {
  if (query) {
    selectLoading.value = true;
    const resData = await getEnterpriseList({ KEYWORDS: query });
    enterpriseList.value = resData.varList;
    selectLoading.value = false;
  }
});
const fnDelete = debounce(
  1000,
  async (BUS_TEXT_LIBRARY_ID) => {
    await ElMessageBox.confirm("确定要删除吗？", {
      type: "warning",
    });
    await setThreeInstitutionalLibrariesDelete({ BUS_TEXT_LIBRARY_ID });
    ElMessage.success("删除成功");
    fnResetPaginationTransfer();
  },
  { atBegin: true }
);
const fnView = async (BUS_TEXT_LIBRARY_ID) => {
  const resData = await getThreeInstitutionalLibrariesView({
    BUS_TEXT_LIBRARY_ID,
  });
  const { info } = await getThreeInstitutionalLibrariesViewText({
    BUS_TEXT_LIBRARY_ID,
  });
  data.viewDialog.info = resData.data;
  data.viewDialog.info.TEXT_INFO = info.TEXT_INFO;
  data.viewDialog.visible = true;
};
const fnAddOrEdit = async (BUS_TEXT_LIBRARY_ID, type) => {
  data.addOrEditDialog.visible = true;
  await nextTick();
  data.addOrEditDialog.type = type;
  if (type === "edit") {
    const resData = await getThreeInstitutionalLibrariesView({
      BUS_TEXT_LIBRARY_ID,
    });
    const { info } = await getThreeInstitutionalLibrariesViewText({
      BUS_TEXT_LIBRARY_ID,
    });
    data.addOrEditDialog.form = resData.data;
    data.addOrEditDialog.form.TEXT_INFO = info.TEXT_INFO;
    data.addOrEditDialog.form.file = addingPrefixToFile([
      { FILEPATH: resData.data.PATH },
    ]);
    const TYPES = [];
    for (let i = 0; i < resData.data.TYPES.length; i++) {
      TYPES.push(resData.data.TYPES[i].CATEGORY_ID);
    }
    data.addOrEditDialog.form.TYPES = TYPES;
    const labels = [];
    for (let i = 0; i < resData.data.labels.length; i++) {
      labels.push(resData.data.labels[i].BUS_LABEL_FACTORY_ID);
    }
    data.addOrEditDialog.form.labels = labels;
  }
};
const fnJoinLocal = debounce(
  1000,
  async (BUS_TEXT_LIBRARY_ID) => {
    await ElMessageBox.confirm("确定要将此条数据添加到本地？", {
      type: "warning",
    });
    await setThreeInstitutionalLibrariesJoinLocal({ BUS_TEXT_LIBRARY_ID });
    ElMessage.success("添加成功");
    fnResetPaginationTransfer();
  },
  { atBegin: true }
);
</script>

<style scoped></style>
