<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-button type="primary" size="small" icon="Plus" @click="handleAdd"
        v-hasPermi="['business:company:add']">新增</el-button>

      <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['business:standardCompany:remove']">删除</el-button>
      <el-button type="success" icon="Edit" size="small" :disabled="multiple" @click="setEntrustHandle"
        v-hasPermi="['business:standardCompany:setLoopEntrust']">生成循环委托</el-button>
      <el-dropdown trigger="click">
        <el-button type="primary" size="small">
          其它<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="handleCommand(true)" icon="Operation"
              v-if="viewAdviser('business:standardCompany:Adviser')">设置客服</el-dropdown-item>
            <el-dropdown-item @click="handleCommand(false)" icon="Operation"
              v-if="viewAdviser('business:standardCompany:Leader')">设置负责人</el-dropdown-item>
            <el-dropdown-item type="warning" size="small" icon="Download" @click="handleExport"
              v-if="viewAdviser('business:standardCompany:export')">导出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true">
      <el-form class="list-search-container" size="small" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="客户名称：" prop="name">
          <el-input v-model="queryParams.name" style="width: 180px" placeholder="请输入客户名称" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="税号：" prop="socialCreditCode">
          <el-input style="width: 180px" v-model="queryParams.socialCreditCode" placeholder="请输入税号" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="客户负责人：" prop="leaderName">
          <el-input style="width: 180px" v-model="queryParams.leaderName" placeholder="请输入客户负责人" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-form>

    <!-- 列表区 -->
    <el-table v-loading="loading" :data="companyList" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名称" width="230" align="center" prop="name" />
      <el-table-column label="税号" width="180" align="center" prop="socialCreditCode" />
      <el-table-column label="注册省-市-区" width="180" align="center" prop="province">
        <template #default="scope">
          <span>{{
            scope.row.province + "-" + scope.row.city + "-" + scope.row.district
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年收入" align="center" width="100" prop="annualIncome" />
      <el-table-column label="纳税类型" align="center" width="130" prop="taxType" />
      <el-table-column label="是否零申报" width="100" align="center" prop="isZero">
        <template #default="scope">
          <span>{{
            scope.row.isZero === 1 ? "是" : scope.row.isZero === 0 ? "否" : ""
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客服" align="center" prop="adviserName" />
      <el-table-column label="负责人" align="center" prop="leaderName" />

      <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width" :resizable="false"
        fixed="right">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOneEnrust(scope.row)"
            v-hasPermi="['business:standardCompany:setOneEntrust']">单次委托</el-button>
          <el-button link type="primary" size="small" @click="handleInfo(scope.row)"
            v-hasPermi="['business:standardCompany:query']">详细信息</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 表单 -->
    <company-form ref="companyRef" :get-list="getList"></company-form>
    <set-entrust-dialog ref="setEntrustDialogRef" :get-list="getList" />
    <set-one-entrust-dialog ref="setOneEntrustDialogRef" :get-list="getList" />
    <add ref="addRef" :get-list="getList"></add>

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

    <!-- 设置客服和负责人对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable :close-on-click-modal="false">
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="100">
        <el-form-item :label="title" :prop="content">
          <el-autocomplete :fetch-suggestions="querySearchAsync" :trigger-on-focus="true" v-model="creatorName"
            :placeholder="content" @select="handleSelect" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Company">
  import { listUser } from "@/api/system/user";
  import SetEntrustDialog from "./setEntrustDialog";
  import useUserStore from "@/store/modules/user";
  import SetOneEntrustDialog from "./setOneEntrustDialog";
  import {
    listStandardCompany,
    delStandardCompany,
    updateStandardCompanyName,
    updateStandardCompanyAdviser,
    exportCompany,
  } from "@/api/business/standardCompany";
  import companyForm from "./form";
  import add from "./add.vue";
  const { proxy } = getCurrentInstance();

  // /** 字典数组区 */
  // /** 查询 对象 */

  const companyList = ref([]);
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const selections = ref([]);
  const title = ref("");
  const content = ref("");
  const creatorName = ref("");
  const total = ref(0);
  const userList = ref([]);
  const open = ref(false);
  const dateRange = ref([]);
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  const links = ref([]);
  const adviserOpen = ref(true);
  const userId = ref();
  const setEntrustDialogRef = ref(null);
  const setOneEntrustDialogRef = ref(null);

  /** 查询对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time",
  });

  /** 用户对象 */
  const queryUser = {
    pageNum: 1,
    pageSize: 20,
    userName: null,
    phonenumber: null,
    status: null,
    deptId: null,
    userId: null,
    nickName: null,
  };

  /***********************  方法区  ****************************/
  onActivated(() => {
    // 你的逻辑
    getList();
  });
  /** 查询company列表 */
  function getList() {
    links.value.length = 0;
    loading.value = true;

    Promise.all([
      listStandardCompany(queryParams.value),
      listUser(proxy.addDateRange(queryUser, dateRange.value)),
    ]).then((result) => {
      companyList.value = result[0].rows;
      total.value = result[0].total;
      userList.value = result[1].rows;
      loading.value = false;
      linkList();
    }).catch;
  }

  function linkList() {
    userList.value.forEach((item) => {
      links.value.push({ value: item.nickName });
    });
  }

  /** 输入框输出建议 */
  const querySearchAsync = (queryString, cb) => {
    console.log(links);
    const results = queryString
      ? links.value.filter(createFilter(queryString))
      : links.value;
    cb(results);
  };

  function createFilter(queryString) {
    return (restaurant) => {
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      );
    };
  }

  function setEntrustHandle() {
    setEntrustDialogRef.value.open({
      selections: selections.value,
    });
  }

  function handleOneEnrust(row) {
    setOneEntrustDialogRef.value.open(row);
  }

  /** 对话框确定按钮操作 */
  function submitForm() {
    const id = ids.value;
    const index = userList.value.findIndex(
      (item) => item.nickName == creatorName.value
    );

    if (index != -1) userId.value = userList.value[index].userId;
    else {
      proxy.$modal.msgError("请选择人员");
      return;
    }
    if (adviserOpen.value) {
      updateStandardCompanyAdviser(id, userId.value).then((response) => {
        proxy.$modal.msgSuccess("设置完成!");
        creatorName.value = "";
        open.value = false;
        getList();
      });
    } else {
      updateStandardCompanyName(id, userId.value).then((response) => {
        proxy.$modal.msgSuccess("设置完成!");
        creatorName.value = "";
        open.value = false;
        getList();
      });
    }
  }

  function viewAdviser(quer) {
    return permissions.includes(all_permission) || permissions.includes(quer);
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.name = "";
    queryParams.value.socialCreditCode = "";
    queryParams.value.leaderName = "";
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    selections.value = selection;
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 打开修改客服、负责人对话框 */
  function handleCommand(com) {
    adviserOpen.value = com;
    const updateIds = ids.value;
    if (updateIds.length == 0) {
      proxy.$modal.msgError("请至少选择一条数据！");
      return;
    }

    if (com) {
      open.value = true;
      title.value = "设置客服";
      content.value = "输入客服名称";
    } else {
      open.value = true;
      title.value = "设置负责人";
      content.value = "输入负责人名称";
    }
  }

  /** 关闭对话框 */
  function cancel() {
    open.value = false;
    creatorName.value = "";
  }

  /** 新增按钮操作 */
  function handleAdd() {
    proxy.$refs.addRef.open();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm("是否确认删除选中的数据项？")
      .then(function () {
        return delStandardCompany(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功！");
      })
      .catch(() => { });
  }

  /** 导出按钮操作 */
  function handleExport() {
    exportCompany(queryParams.value);
  }

  function handleInfo(row) {
    proxy.$refs.companyRef.open(row.id);
  }

  getList();
</script>