<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:company:remove']">删除</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="handleAdviser()" v-if="viewAdviser('business:company:adviser')" icon="Operation">
              设置客服</el-dropdown-item>
            <el-dropdown-item @click="handleLeader()" v-if="viewAdviser('business:company:leader')" icon="Operation">
              设置负责人</el-dropdown-item>
            <el-dropdown-item type="warning" size="small" icon="Download" @click="handleExport"
              v-if="viewAdviser('business:company:export')">
              导出</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-button style="margin-left: 5px;" type="primary" size="small" icon="Plus"
        @click="exportZero">导入是否零申报</el-button>
    </div>
    <!-- 搜索区 -->
    <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" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery"
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="税号：" prop="socialCreditCode">
        <el-input v-model="queryParams.socialCreditCode" style="width: 200px" placeholder="税号" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户负责人：" prop="leader">
        <el-input v-model="queryParams.leader" style="width: 200px" 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>
    <div v-if="flag && flag2 && tenant.versionId !== '4'">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" >
      <el-tab-pane label=" 全部" name="first">
        </el-tab-pane>
        <el-tab-pane label="我的" name="second">
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 列表区 -->
    <el-table v-loading="loading" :data="list" size="small" border height="100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :resizable="false" align="center" />

      <el-table-column label="公司名称" :resizable="false" min-width="250" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleInfo(scope.row)"
            v-hasPermi="['business:company:info']">{{ scope.row.name }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属区域" prop="provinceCode" :resizable="false" min-width="150" align="center">
        <template #default="scope">
          <span>{{
            scope.row.province + "-" + scope.row.city + "-" + scope.row.district
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年收入" :resizable="false" prop="annualIncome" min-width="100" align="center" />
      <el-table-column label="纳税性质" prop="taxType" min-width="90" :resizable="false" align="center" />
      <el-table-column label="是否零申报" prop="isZero" :resizable="false" width="75" align="center">
        <template #default="scope">
          {{
          scope.row.isZero === 1 ? "是" : scope.row.isZero === 0 ? "否" : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="税号" prop="socialCreditCode" min-width="200" :resizable="false" align="center" />
      <el-table-column label="负责人" prop="leaderName" :resizable="false" min-width="100" align="center" />
      <el-table-column label="客服" min-width="100" prop="adviserName" :resizable="false" align="center" />
      <el-table-column label="客户跟进" :resizable="false" width="65" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleFollow(scope.row)"
            v-hasPermi="['business:company:follow']">跟进</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80" :resizable="false" fixed="right">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleInfo(scope.row)"
            v-hasPermi="['business:company:info']">详细信息</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <!-- <div class="pagination-container"> -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- </div> -->
    <!-- 表单 -->
    <company-form ref="companyRef" :get-list="getList"></company-form>
    <exportColumn ref="exportColumnRef"></exportColumn>
    <add ref="addRef" :get-list="getList"></add>
    <exports ref="exportRef" :get-list="getList"></exports>
    <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable @close="cancel"
      :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 style="width: 100%" :fetch-suggestions="querySearchAsync" :trigger-on-focus="true"
            v-model="selectionName" :placeholder="content" popper-class="my-autocomplete"
            @select="handleSelectEmployee">
            <template #default="{ item }">
              <div style="
                  display: flex;
                  flex-direction: row;
                  justify-content: space-between;
                ">
                <div class="name" style="font-size: 12px">
                  {{ item.nickName }}
                </div>
                <span class="code" style="font-size: 10px; color: darkgrey">{{
                  item.userName
                  }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" size="small" icon="Finished" @click="submitForm">确 定</el-button>
          <el-button size="small" icon="Close" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Crm">
  import exportColumn from "./ExportColumn";
  import companyForm from "./form";
  import { listUser } from "@/api/system/user";
  import add from "./add.vue";
  import exports from "./export.vue"
  import { addBin } from "@/api/business/bin";
  import {
    listCompany,
    getCompany,
    delCompany,
    setCompanyLeader,
    setCompanyAdviser,
    initArea,
  } from "@/api/business/crm/company";
  import useUserStore from "@/store/modules/user";
  const { proxy } = getCurrentInstance();
  /** 字典数组区 */
  const { develop_type } = proxy.useDict("develop_type");
  /** 主页面 变量 */
  const list = ref([]);
  const permissions = useUserStore().permissions;
  const all_permission = "*:*:*";
  const loading = ref(false);
  const tenant = useUserStore().tenant;
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const choiceType = ref("");
  const flag = ref(checkPermission(['business:company:person']))
  const flag2 = ref(checkPermission(['business:company:myself']))
  const activeName = flag.value ? ref('first') : ref('second');
  const open = ref(false);
  const title = ref("");
  const content = ref("");
  const oneself = ref(false);
  const selectionName = ref("");
  const selectionUser = ref({});
  const exportColumnRef = ref(null);

  /** 查询 对象 */
  const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    orderByColumn: "create_time",
    name: null,
    standard: null,
    num: null,
    principal: tenant.versionId !== '4' && !flag.value ? useUserStore().user.userId : null,
  });

  /***********************  列表页方法 ****************************/

  /** 查询项目信息列表 */
  function getList() {
    loading.value = true;
    listCompany(queryParams.value).then((response) => {
      list.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  //判断是否有权限
  function viewAdviser(quer) {
    return permissions.includes(all_permission) || permissions.includes(quer);
  }
  function handleClick(tab) {
    console.log(tab.props.name)
    if (tab.props.name === "second") {
      oneself.value = true
      handleOneself()
    } else {
      oneself.value = false
      handleOneself()
    }
  }
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    if (activeName.value != null && activeName.value === 'second') {
      queryParams.value.principal = useUserStore().user.userId;
    }
    handleQuery();
  }

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

  /** 新增按钮操作 */
  function handleAdd() {
    proxy.$refs.addRef.open();
  }
  /** 新增导入操作 */
  function exportZero() {
    proxy.$refs.exportRef.open();
  }
  /** 是否为自己负责 */
  function handleOneself() {
    if (oneself.value) {
      queryParams.value.principal = useUserStore().user.userId;
    } else {
      queryParams.value.principal = null;
    }
    getList();
  }
  function checkPermission(templatePermission) {
    const all_permission = "*:*:*";
    const permissions = useUserStore().permissions;
    const hasPermissions = permissions.some((permission) => {
      return (
        all_permission === permission || templatePermission.includes(permission)
      );
    });
    return hasPermissions;
  }
  /** 修改按钮操作 */
  function handleUpdate(row) {
    const id = row.id || ids.value;
    // console.log(id)
    proxy.$refs.companyRef.open(id);
  }

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

  /** 导出按钮操作 */
  function handleExport() {
    exportColumnRef.value.open(queryParams.value);
  }
  function handleAdviser() {
    const updateIds = ids.value;
    if (updateIds.length == 0) {
      proxy.$modal.msgError("请至少选择一条数据！");
      return;
    }
    open.value = true;
    title.value = "设置客服";
    content.value = "输入客服名称";
    choiceType.value = "adviser";
  }
  function handleLeader() {
    const updateIds = ids.value;
    if (updateIds.length == 0) {
      proxy.$modal.msgError("请至少选择一条数据！");
      return;
    }
    open.value = true;
    title.value = "设置负责人";
    content.value = "输入负责人名称";
    choiceType.value = "leader";
  }
  function handleInfo(row) {
    proxy.$refs.companyRef.open(row.id);
  }
  /** 输入框输出建议 */
  const querySearchAsync = (queryString, cb) => {
    const query = { keyword: queryString };
    listUser(query).then((res) => {
      cb(res.rows);
      console.log(res.rows);
    });
  };
  function handleSelectEmployee(item) {
    console.log(item);
    selectionName.value = item.nickName;
    selectionUser.value = item;
  }

  function submitForm() {
    if (selectionUser.value == null || selectionUser.value.userId == null) {
      proxy.$modal.msgError("请选择用户！");
      return;
    }
    if (choiceType.value == "adviser") {
      setCompanyAdviser({
        ids: ids.value,
        adviserId: selectionUser.value.userId,
      }).then((response) => {
        proxy.$modal.msgSuccess("设置完成!");
        open.value = false;
        cancel();
        getList();
      });
    } else if (choiceType.value == "leader") {
      setCompanyLeader({
        ids: ids.value,
        leaderId: selectionUser.value.userId,
      }).then((response) => {
        proxy.$modal.msgSuccess("设置完成!");
        open.value = false;
        cancel();
        getList();
      });
    }
  }
  function handleFollow(row) {
    proxy.$refs.companyRef.open(row.id, "follow-form");
  }
  function handleArea() {
    initArea();
  }

  function cancel() {
    open.value = false;
    selectionName.value = "";
    selectionUser.value = "";
  }
  getList();
</script>
<style scope></style>