<script setup>
import { computed, ref } from "vue";
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { ficcManageInterface, customInterence } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import Readia from "@/views/custom_manage/custom/components/ReadDialog.vue";
import intervewDia from "./apply/components/interviewDia.vue";
import moveCustomDia from "./apply/components/moveCustomDia.vue";
import { useReadia } from "@/views/custom_manage/custom/hooks/customlistHook";
import { useMoveContacts } from './hooks/use-ficcMan.js'
import moment from "moment";
import DatePicker from "vue-datepicker-next";

const router = useRouter()

//导出url
const exportUrl = computed(() => {
  let url = import.meta.env.VITE_APP_API_ROOT;
  let param_token = localStorage.getItem("auth") || "";
  let sourceType = activeName.value === 2 ? "中文官网" : "英文官网";
  const recodeUrl = `/yb/apply_record/listV2/export?States=${search_type.value}&ApplyStatus=${custom_apply_type.value}&KeyWord=${search_txt.value}&${param_token}`;
  const official = `/custom/official/user/list/export?SourceType=${sourceType}&KeyWord=${search_txt.value}&${param_token}`;
  url += activeName.value === 1 ? recodeUrl : official;
  return url;
});
//tabs数组,根据Role决定是否显示后两个
const Tabs = computed(() => {
  //判断Role，为销售时不显示后面两个
  let roleType = localStorage.getItem("Role");
  if (!["ficc_admin", "admin"].includes(roleType)) {
    return [getTabs[0]];
  } else {
    return getTabs;
  }
});

const applyArr = [
  { name: "已申请", value: "已申请" },
  { name: "未申请", value: "未申请" },
];
const getTabs = [
  { name: "弘则研报", type: 1 },
  { name: "中文官网", type: 2 },
  { name: "英文官网", type: 3 },
];
const statusArr = [
  { name: "潜在用户", value: 1 },
  /* { name: "权益用户", value: 2 }, */
  { name: "流失", value: 3 },
  { name: "冻结", value: 4 },
  { name: "试用暂停", value: 5 },
];
const groupArr = [
  { name: "楼颖丹组", value: "楼颖丹组" },
  { name: "时代组", value: "时代组" },
  { name: "岳梦琳组", value: "岳梦琳组" },
  { name: "权益组", value: "权益组" },
];

/* 获取表格数据 */
const tableLoading = ref(false);
const tableData = ref([]);
const tableColums = ref([]);
const activeName = ref(1);
const activeItem = { name: "弘则研报", type: 1 };

const total = ref(0);
const pageSize = ref(10);
const page_no = ref(1);
const search_txt = ref("");
const search_type = computed(() => custom_type.value.join(","));
const custom_type = ref([]);
const custom_apply_type = ref("");
const group_type = ref("");
const date_range = ref([]);
async function getTableData() {
  tableLoading.value = true;
  const res =
    activeName.value == 1
      ? await ficcManageInterface.applyRecordListV2({
          PageSize: pageSize.value,
          CurrentIndex: page_no.value,
          KeyWord: search_txt.value,
          States: search_type.value,
          ApplyStatus: custom_apply_type.value,
          MarkGroup: group_type.value,
          StartDate: date_range.value[0],
          EndDate: date_range.value[1],
        })
      : await customInterence.trialList({
          PageSize: pageSize.value,
          CurrentIndex: page_no.value,
          SourceType:
            activeName.value == 2
              ? "中文官网"
              : activeName.value == 3
              ? "英文官网"
              : "",
          KeyWord: search_txt.value,
          MarkGroup: group_type.value,
          StartDate: date_range.value[0],
          EndDate: date_range.value[1],
        });

  tableLoading.value = false;
  if (res.Ret === 200) {
    tableData.value = res.Data.List || [];
    total.value = res.Data.Paging.Totals;
  }
}
getTableData();

//表格列
const getTableColums = (type) => {
  return type === 1
    ? [
        {
          label: "姓名",
          key: "RealName",
        },
        {
          label: "手机号码",
          key: "Mobile",
        },
        {
          label: "邮箱",
          key: "Email",
        },
        {
          label: "最新提交时间",
          key: "LastTime",
          minwidthsty: 140,
        },
        {
          label: "累计提交次数",
          key: "ApplyTotal",
        },
        {
          label: "最近一次阅读时间",
          key: "LastViewTimeStr",
          minwidthsty: 140,
        },
        {
          label: "累计阅读次数",
          key: "ViewTotal",
        },
        {
          label: "公司",
          key: "CompanyName",
        },
        {
          label: "原销售",
          key: "OriginSellerName",
        },
        {
          label: "来源",
          key: "SourceStr",
        },
        {
          label: "申请品种",
          key: "Permission",
        },
        {
          label: "申请类型",
          key: "ApplyStatus",
        },
        {
          label: "用户状态",
          key: "Status",
        },
      ]
    : type === 2
    ? [
        {
          label: "企业名称",
          key: "CompanyName",
        },
        {
          label: "姓名",
          key: "RealName",
        },
        {
          label: "手机号/邮箱",
          key: "Phone",
        },
        {
          label: "所属行业",
          key: "Industry",
        },
        {
          label: "申请时间",
          key: "CreateTimeStr",
        },
        {
          label: "申请品种",
          key: "ProductInfo",
        },
      ]
    : [
        {
          label: "企业名称",
          key: "CompanyName",
        },
        {
          label: "姓名",
          key: "RealName",
        },
        {
          label: "邮箱",
          key: "Email",
        },
        {
          label: "信息",
          key: "Message",
        },
        {
          label: "发送时间",
          key: "CreateTimeStr",
        },
      ];
};
tableColums.value = getTableColums(1);

function changeQuery() {
  page_no.value = 1;
  getTableData();
}

// 页码改变事件
function handleCurrentChange(page, index) {
  page_no.value = page;
  getTableData();
}

/* top的点击事件 */
function handleTabsClick(item) {
  if (activeName.value !== item.type) {
    activeName.value = item.type;
    tableColums.value = getTableColums(activeName.value);
  }
  //重置筛选项
  search_txt.value = "";
  custom_type.value = [];
  custom_apply_type.value = [];
  date_range.value = [];
  group_type.value = "";

  changeQuery();
}

const { readId, isRead, cancelRead, lookReport, readTit } = useReadia();
/* 表格行的点击事件 */
function handleRowClick(row, key) {
  if (key === "ViewTotal") {
    lookReport(row);
  }
}

/* 表格行的样式 */
function handleRowStyle(key) {
  const style = {
    ViewTotal: "color: #409eff; cursor: pointer",
  };
  return style[key] ? style[key] : "";
}

/* 表格行的数据处理 */
function handleRowContent(row, key) {
  if (["LastTime", "LastViewTimeStr"].includes(key)) {
    return row[key] && row[key].length > 0
      ? moment(row[key]).format("YYYY-MM-DD HH:mm:ss")
      : "";
  } else {
    return row[key];
  }
}

//删除
function delHandle(item) {
  ElMessageBox.confirm("是否删除该申请记录", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ficcManageInterface
        .delPotentialUser({ UserId: Number(item.UserId) })
        .then((res) => {
          if (res.Ret === 200) {
            ElMessage({
              type: "success",
              message: "删除成功!",
            });
            getTableData();
          }
        });
    })
    .catch(() => {});
}

//打开标记分组弹窗
const isChooseGroupDialogShow = ref(false);
const choosed_row = ref(null);
const choosed_group = ref("");
function handleChooseGroup(row) {
  choosed_row.value = row;
  choosed_group.value = "";
  isChooseGroupDialogShow.value = true;
}

const isShowDia = ref(false)
//标记分组
async function chooseGroup() {
  if (!choosed_group.value) {
    ElMessage.warning("请选择分组");
    return;
  }
  const { ApplyRecordId, UserId, Id } = choosed_row.value;
  //请求接口
  const res =
    activeName.value === 1
      ? await customInterence.markApplyUser({
          ApplyRecordId,
          UserId,
          GroupName: choosed_group.value,
        })
      : await customInterence.markOfficialUser({
          Id,
          GroupName: choosed_group.value,
        });

  if (res.Ret !== 200) return;
  ElMessage.success("标记分组成功");
  isChooseGroupDialogShow.value = false;
  choosed_group.value = "";
  getTableData();
}

const { isShowMoveDia,dealObj,moveHandle,closeMove } = useMoveContacts()
</script>
<template>
  <div class="container-userapplication">
    <div class="userapplication-top">
      <div class="top-tabs">
        <el-radio-group
          v-model="activeName"
          @change="handleTabsClick(activeItem)"
        >
          <el-radio-button
            :label="item.type"
            v-for="item in Tabs"
            :key="item.name"
            >{{ item.name }}</el-radio-button
          >
        </el-radio-group>
      </div>
    </div>
    <el-card style="margin-top: 20px">
      <div class="export-select">
        <date-picker
          v-model:value="date_range"
          type="date"
          range
          value-type="format"
          :placeholder="`请选择${
            activeName === 1 ? '提交' : activeName === 2 ? '申请' : '发送'
          }时间`"
          @change="changeQuery"
        >
        </date-picker>
        <el-select
          v-if="activeName == 1"
          v-model="custom_apply_type"
          placeholder="请选择申请类型"
          style="width: 160px"
          clearable
          @change="changeQuery"
        >
          <el-option
            v-for="item in applyArr"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <el-select
          v-if="activeName == 1"
          v-model="custom_type"
          placeholder="请选择用户状态"
          style="width: 200px"
          clearable
          multiple
          @change="changeQuery"
        >
          <el-option
            v-for="item in statusArr"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="group_type"
          placeholder="请选择分组"
          style="width: 160px"
          clearable
          @change="changeQuery"
        >
          <el-option
            v-for="item in groupArr"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <el-input
          placeholder="姓名/手机号/邮箱/公司名称"
          v-model="search_txt"
          clearable
          style="max-width: 240px"
          @input="changeQuery"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table
        :data="tableData"
        v-loading="tableLoading"
        element-loading-text="数据加载中..."
        border
      >
        <el-table-column
          v-for="item in tableColums"
          :key="item.label"
          :label="item.label"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          align="center"
        >
          <template #default="{ row }">
            <div v-if="item.key == 'CompanyName'">
              <span
                style="color: #409eff; cursor: pointer"
                v-if="row.CompanyId > 1"
                @click="
                  router.push({
                    path: '/RaiDetail',
                    query: {
                      id: row.CompanyId,
                    },
                  })
                "
                >{{ row.UserCompanyName || row.CompanyName }}</span
              >
              <span v-else>{{ row.UserCompanyName || row.CompanyName }}</span>
            </div>
            <span
              v-else
              @click="handleRowClick(row, item.key)"
              :style="handleRowStyle(item.key)"
              >{{ handleRowContent(row, item.key) }}</span
            >

          </template>
        </el-table-column>
        <el-table-column label="分组" align="center">
          <template #default="{ row }">
            <span>{{ row.MarkGroup }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <div v-if="activeName == 1">
              <span
                class="editsty"
                v-if="row.OpStatus === 0 && row.IsMove === 0"
                @click="handleChooseGroup(row)"
                >标记</span
              >
            </div>
            <div v-else>
              <span
                class="editsty"
                v-if="row.Status === '待处理'"
                @click="handleChooseGroup(row)"
                >标记</span
              >
            </div>
            <span
              class="editsty"
              v-if="activeName == 1 && row.IsMove === 0"
              @click="moveHandle(row)"
              >移动</span
            >
            <!-- <span class="editsty" style="color:#ff0000" v-if="row.DelBtn" @click="delHandle(row)">删除</span> -->
          </template>
        </el-table-column>
        <template #empty>
          <div style="padding: 20px 0">
            <img
              src="~@/assets/img/data_m/table_no.png"
              alt=""
              style="display: block; width: 135px; height: 90px; margin: 0 auto"
            />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <el-col :span="24" class="toolbar">
        <m-page
          :total="total"
          :page_no="page_no"
          :pageSize="10"
          @handleCurrentChange="handleCurrentChange"
        />
      </el-col>
    </el-card>
    <!-- 阅读报告弹窗 -->
    <Readia
      :readId="readId"
      :lookRead="isRead"
      :title="readTit"
      @cancelRead="cancelRead"
    >
    </Readia>
    <!-- 处理弹窗 -->
    <!-- <intervewDia
      :isShowDia="isShowDia"
      :item="dealObj"
      :activeName="activeName"
    /> -->
    <!-- 移动弹窗 -->
    <moveCustomDia
      :isShow="isShowMoveDia"
      :item="dealObj"
      @close="closeMove"
    />
    <!-- 标记分组弹窗 -->
    <el-dialog
      draggable
      v-model="isChooseGroupDialogShow"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      title="标记"
      width="480px"
      center
      @close="isChooseGroupDialogShow = false"
    >
      <div class="dialog-container">
        <div class="select" style="display: flex; align-items: center">
          <span>分组：</span>
          <el-select
            v-model="choosed_group"
            placeholder="请选择分组"
            style="flex: 1; margin-left: 10px"
          >
            <el-option
              v-for="item in groupArr"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <div style="display: flex; justify-content: center; margin: 20px 0">
        <el-button
          type="primary"
          style="width: 80px; marginright: 24px"
          @click="chooseGroup"
          >保存</el-button
        >
        <el-button
          type="primary"
          plain
          style="width: 80px"
          @click="isChooseGroupDialogShow = false"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.container-userapplication {
  min-width: 1500px;
  .userapplication-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid #ececec;
    padding: 20px 30px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
  .top-tabs {
    display: flex;
    .active {
      background-color: #409eff;
      color: #fff;
    }
    span {
      display: inline-block;
      box-sizing: border-box;
      padding: 0 24px;
      line-height: 38px;
      height: 40px;
      background: #ecf5ff;
      border: 1px solid #b3d8ff;
      opacity: 1;
      font-weight: 500;
      font-size: 16px;
      color: #409eff;
      border-radius: 4px;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .export-select {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 20px;
    .el-input {
      margin-left: auto;
    }
  }

  :deep(.el-dialog .el-input) {
    width: 100%;
  }

}
.container-userapplication :deep(.mx-datepicker) {
  width: 200px !important;
}

</style>
