<template>
  <div class="app-container">
    <el-form
        v-show="showSearch"
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        label-width="68px"
    >
      <el-form-item label="企业名称" prop="name">
        <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入企业名称"
            size="default"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="所属站点" prop="tenantId">
        <SiteOptions v-model="queryParams.tenantId" :site-list="siteList" />
      </el-form-item> -->

      <el-form-item>
        <el-button
            icon="search"
            size="default"
            type="primary"
            @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="refresh" size="default" @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            icon="plus"
            plain
            size="default"
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            icon="upload"
            plain
            size="default"
            type="info"
            @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <!--            <el-col :span="1.5">-->
      <!--              <el-button-->
      <!--                  icon="download"-->
      <!--                  plain-->
      <!--                  size="default"-->
      <!--                  type="warning"-->
      <!--                  @click="handleExport"-->
      <!--              >导出-->
      <!--              </el-button-->
      <!--              >-->
      <!--            </el-col>-->
      <el-col :span="1.5">
        <el-button
            :disabled="!ids.length"
            icon="delete"
            type="danger"
            @click="handleDelete()"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="dataList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" label="机构名称" prop="name"/>
      <el-table-column align="center" label="统一社会信用代码" prop="code"/>
      <el-table-column align="center" label="主要研究方向" prop="research"/>

      <!-- <el-table-column label="站点" align="center">
        <template #default="{ row }">
          {{ siteList.find((el) => el.id === row.tenantId)?.name ?? "无" }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="所在地" prop="address"/>
      <el-table-column align="center" label="申请时间">
        <template #default="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button
              icon="edit"
              size="small"
              type="text"
              @click="handleDetail(row.id)"
          >修改
          </el-button>
          <el-button
              icon="delete"
              size="small"
              type="text"
              @click="handleDelete(row.id)"
          >删除
          </el-button>
          <el-button
              icon="edit"
              size="small"
              type="text"
              @click="openAssignAccount(row.id)"
          >分配账号
          </el-button>
          <el-button
              icon="edit"
              size="small"
              type="text"
              @click="openResetPassword(row.id)"
          >重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog
        v-model="upload.open"
        :title="upload.title"
        append-to-body
        width="400px"
    >
      <el-upload
          ref="uploadRef"
          :action="upload.url"
          :auto-upload="false"
          :disabled="upload.isUploading"
          :headers="upload.headers"
          :limit="1"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          accept=".xlsx, .xls"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <!-- <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="importTemplate"
            >下载模板
            </el-link
            >
            <br/>
            <span>科研机构导入说明:</span>
            <ol style="text-align: left">
              <li>
                <span>研究方向 多个用|隔开 (人工智能|量子计算)</span>
              </li>
              <li>
                <span>所属领域 (>拼接上下级 多个用|隔开)
                  航空航天>航天技术>运载火箭技术|生物与新医药>中药、天然药物>创新药物研发技术</span>
              </li>
            </ol>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="showAssignAccount"
        append-to-body
        title="分配账号"
        width="400px"
    >
      <el-form
          ref="assignAccountFormRef"
          :model="assignAccountForm"
          :rules="assignAccoutRules"
          label-width="80px"
      >
        <el-form-item label="手机号" prop="username">
          <el-input
              v-model="assignAccountForm.username"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="assignAccountForm.password"
              show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAssignAccount"
          >确 定
          </el-button>
          <el-button @click="closeAssignAccount">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
        v-model="showResetPassword"
        append-to-body
        title="重置密码"
        width="400px"
    >
      <el-form
          ref="resetPasswordFormRef"
          :model="resetPasswordForm"
          :rules="assignAccoutRules"
          label-width="80px"
      >
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="resetPasswordForm.password"
              show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitResetPassword"
          >确 定
          </el-button>
          <el-button @click="closeResetPassword">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Enterprise" setup>
import {
  allocateAccount,
  casResearchDelete, casResearchImportData,
  getAccount,
  researchList,
  resetPassword,
} from "@/api/dataList/research";
import md5 from "js-md5";
import {getToken} from "@/utils/auth";
import {blobValidate} from "@/utils/ruoyi";
import {saveAs} from "file-saver";
import {reactive, ref, toRefs} from "vue";
import {useRouter} from "vue-router";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

const router = useRouter();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // examine_status: 2,
    name: undefined,
    // tenantId: undefined,
  },
});

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/business/casResearch/importData",
});

const {queryParams} = toRefs(data);
const showSearch = ref(true);
// const siteList = ref([]);
const loading = ref(true);
const total = ref(0);
const dataList = ref([]);

const ids = ref([]);
const handleSelectionChange = (selection) => {
  ids.value = selection.map((el) => el.id);
};

/** 研究机构列表 */
const getList = async () => {
  loading.value = true;
  const resp = await researchList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};
// 获取站点列表
// const getSiteList = async () => {
//   const resp = await tenantSelect();
//   siteList.value = resp.rows;
// };
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const assignAccoutRules = {
  username: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  password: [{required: true, message: "请输入密码", trigger: "blur"}],
  vipType: [{required: true, message: "请选择会员类型", trigger: "change"}],
  expireTime: [
    {required: true, message: "请选择到期时间", trigger: "change"},
  ],
};
const showAssignAccount = ref(false);
const assignAccountForm = reactive({
  username: undefined,
  password: undefined,
});
const assignAccountFormRef = ref();
const resetPasswordForm = reactive({
  password: undefined,
});
const resetPasswordFormRef = ref();
const showResetPassword = ref(false);

const openAssignAccount = async (id) => {
  resetForm();
  const {have, data} = await getAccount(id);
  if (have) {
    ElMessageBox.alert(`已经存在账号：${data}`, "账号已经存在");
  } else {
    assignAccountForm.id = id;
    showAssignAccount.value = true;
  }
};

const openResetPassword = async (id) => {
  resetForm();
  const {have, userId} = await getAccount(id);
  if (have) {
    resetPasswordForm.id = userId;
    showResetPassword.value = true;
  } else {
    ElMessageBox.alert(`尚未分配账号，请先分配账号`, "尚未分配账号");
  }
};
const resetForm = () => {
  if (resetPasswordFormRef.value) {
    resetPasswordFormRef.value.resetFields();
  }
  if (assignAccountFormRef.value) {
    assignAccountFormRef.value.resetFields();
  }
  resetPasswordForm.password = undefined;
  assignAccountForm.username = undefined;
  assignAccountForm.password = undefined;
};
const closeResetPassword = () => {
  resetForm();
  showResetPassword.value = false;
};
const closeAssignAccount = () => {
  resetForm();
  showAssignAccount.value = false;
};

const submitAssignAccount = async () => {
  await assignAccountFormRef.value.validate();
  await allocateAccount({
    ...assignAccountForm,
    password: md5(assignAccountForm.password),
  });
  ElMessage.success("账号分配成功");
  showAssignAccount.value = false;
};

const submitResetPassword = async () => {
  await resetPasswordFormRef.value.validate();
  await resetPassword(resetPasswordForm.id, md5(resetPasswordForm.password));
  ElMessage.success("密码重置成功");
  showResetPassword.value = false;
};

//TODO:
/** 开通vip操作 */
const vipData = reactive({
  vipForm: {userType: "1"},
});
const {vipForm} = toRefs(vipData);
const showOpenVip = ref(false);
const vipFormRef = ref();

// const submitVip = async () => {
//   await vipFormRef.value.validate();
//   if (vipForm.value.id) {
//     await updateCasVip(vipForm.value);
//     ElMessage.success("会员修改成功");
//   } else {
//     await openCasVip(vipForm.value);
//     ElMessage.success("会员开通成功");
//   }
//   showOpenVip.value = false;
// };

const resetVipForm = () => {
  vipForm.value = {userType: "1"};
  if (vipFormRef.value) {
    vipFormRef.value.resetFields();
  }
};

const closeVip = () => {
  resetVipForm();
  showOpenVip.value = false;
};
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [];
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
const handleAdd = () => {
  router.push({
    path: "/dataList/research-institutions/edit",
  });
};
const handleDetail = (id) => {
  router.push({
    path: "/dataList/research-institutions/edit",
    query: {id},
  });
};
const uploadRef = ref(null);

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
}

/** 下载模板操作 */
async function importTemplate() {
  const blob = await casResearchImportData()
  saveAs(blob, "科研机构导入模板.xlsx");
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.handleRemove(file);
  ElMessageBox.alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
      "导入结果",
      {dangerouslyUseHTMLString: true}
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

const handleDelete = async (id) => {
  const delIds = id || ids.value.join(",");
  ElMessageBox.confirm(`是否确认删除编号为${delIds}的数据项？`)
      .then(async () => {
        await casResearchDelete(delIds);
        getList();
        ElMessage.success("删除成功");
      })
      .catch(() => {
      });
};

let downloadLoadingInstance;
const download = (url, filename) => {
  downloadLoadingInstance = ElLoading.service({
    text: "正在下载数据，请稍候",
    background: "rgba(0, 0, 0, 0.7)",
  });
  return request
      .get(url, {
        // transformRequest: [
        //   (params) => {
        //     return tansParams(params);
        //   },
        // ],
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        responseType: "blob",
      })
      .then(async (data) => {
        const isLogin = await blobValidate(data);
        if (isLogin) {
          const blob = new Blob([data]);
          saveAs(blob, filename);
        } else {
          const resText = await data.text();
          const rspObj = JSON.parse(resText);
          const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
          ElMessage.error(errMsg);
        }
        downloadLoadingInstance.close();
      })
      .catch((r) => {
        console.error(r);
        ElMessage.error("下载文件出现错误，请联系管理员！");
        downloadLoadingInstance.close();
      });
};

const handleExport = () => {
  ElMessageBox.confirm(`是否确认企业列表？`).then(() => {
    download(
        `/business/enterprise/export`,
        `企业信息(${dayjs().format("YYYYMMDDHHmmss")}).xlsx`
    );
  });
};
getList();
// getSiteList();
</script>
