<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:channel:add']"
        >新增</el-button
      >

      <el-button
        type="danger"
        size="small"
        icon="Delete"
        :disabled="multiple"
        @click="handleDelete"
        v-hasPermi="['business:channel:remove']"
        >删除</el-button
      >

      <!--<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
    </div>
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      size="small"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="渠道名称：" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入渠道名称"
          style="width: 150px"
          size="small"
          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-table
      v-loading="loading"
      :data="channelList"
      size="small"
      border
      height="100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" type="index" /> -->
      <el-table-column label="渠道名称" align="center" prop="name">
        <template #default="scope">
          <el-input
            v-if="scope.row.isAdd"
            v-model="scope.row.name"
            size="small"
            placeholder="请输入渠道"
          ></el-input>
          <el-input
            v-else-if="scope.row.isEdit"
            size="small"
            v-model="scope.row.name"
          ></el-input>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="categoryShow"
        label="渠道类别"
        align="center"
        prop="channelCategoryName"
      />
      <el-table-column label="负责人" align="center" prop="creatorName">
        <template #default="scope">
          <el-autocomplete
            size="small"
            v-if="scope.row.isEdit || scope.row.isAdd"
            v-model="scope.row.creatorName"
            :fetch-suggestions="querySearchAsync"
            style="width: 100%"
            :trigger-on-focus="true"
            placeholder="请输入负责人"
            @select="handleSelect"
          />
          <span v-else>{{ scope.row.creatorName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="添加时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template #default="scope">
          <template v-if="!scope.row.isEdit && !scope.row.isAdd">
            <el-button
              v-show="!scope.row.isEdit && !scope.row.isAdd"
              link
              type="warning"
              size="small"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:channel:edit']"
              >修改</el-button
            >
            <el-button
              v-show="!scope.row.isEdit && !scope.row.isAdd"
              link
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:channel:remove']"
              >删除</el-button
            >
          </template>
          <template v-if="scope.row.isEdit || scope.row.isAdd">
            <el-button
              v-show="scope.row.isEdit || scope.row.isAdd"
              link
              type="primary"
              size="small"
              @click="handleSave(scope.row)"
              >保存</el-button
            >
            <el-button
              v-show="scope.row.isEdit || scope.row.isAdd"
              link
              size="small"
              @click="handCancel(scope.row)"
              >取消</el-button
            >
          </template>
        </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"
    />
  </div>
</template>

<script setup name="Channel">
import { listUser } from "@/api/system/user";
import {
  listChannel,
  delChannel,
  listCategory,
  updateChannel,
  addChannel,
} from "@/api/business/channel";
import { ref } from "vue";
// import channelForm from "./form"
const { proxy } = getCurrentInstance();
/** 字典数组区 */
/** 查询 对象 */

const channelList = ref([]);
const categoryList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
const userList = ref([]);
const nickNameLits = ref([]);
const categoryShow = ref(false);
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  code: null,
  name: null,
  contact: null,
  phone: null,
  orderByColumn: "create_time",
  email: null,
  owner: null,
  status: null,
  createTime: null,
  employeeId: null,
  creatorName: "",
  channelCategoryId: null,
  channelCategoryName: null,
  isEdit: false,
  isAdd: false,
});

const queryNickName = ref({
  nickName: null,
});

/** 渠道类型对象 */
const queryCategory = {
  pageNum: 1,
  pageSize: 10,
  orderByColumn: "create_time",
  id: null,
  name: null,
};

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

const LinkItem = {
  value: "",
};

const links = ref([]);

/***********************  方法区  ****************************/

/** 查询渠道列表 */
function getList() {
  Promise.all([
    listChannel(queryParams.value),
    listUser(proxy.addDateRange(queryUser, dateRange.value)),
    listCategory(queryCategory.value),
  ]).then((result) => {
    channelList.value = result[0].rows;
    userList.value = result[1].rows;
    categoryList.value = result[2].rows;
    total.value = result[0].total;
    loading.value = false;
    userNameList();
  }).catch;
}

/** 输入框输出建议 */
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 userNameList() {
  /** 比较user表和渠道表的员工ID */
  links.value.length = 0;
  for (let i = 0; i < userList.value.length; i++) {
    links.value.push({ value: userList.value[i].nickName });
    for (let j = 0; j < channelList.value.length; j++) {
      if (userList.value[i].userId == channelList.value[j].employeeId) {
        channelList.value[j].creatorName = userList.value[i].nickName;
      }
    }
  }

  /** 比较渠道类别表和渠道表的类别ID */
  for (let i = 0; i < categoryList.value.length; i++) {
    for (let j = 0; j < channelList.value.length; j++) {
      if (categoryList.value[i].id == channelList.value[j].channelCategoryId) {
        channelList.value[j].channelCategoryName = categoryList.value[i].name;
      }
    }
  }
}

/** 取消按钮操作 */
function handCancel(row) {
  if (row.isEdit) row.isEdit = false;
  else channelList.value.length = channelList.value.length - 1;
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  // 此处必须进行深拷贝，否则添加的明细，将都指向了一个对象
  const _newSource = JSON.parse(JSON.stringify(queryParams.value));
  channelList.value.push(_newSource);
  handleSourceCurrentChange(_newSource);
}

/** 修改新增属性判断 */
function handleSourceCurrentChange(row) {
  row.isAdd = true;
}

/** 保存按钮操作 */
function handleSave(row) {
  if (
    row.name.length > 0 &&
    row.creatorName.length > 0 &&
    row.name !== null &&
    row.creatorName !== null
  ) {
    const index = userList.value.findIndex(
      (item) => item.nickName == row.creatorName
    );

    if (index != -1) {
      row.employeeId = userList.value[index].userId;
    }

    console.log(row);
    if (row.isAdd) {
      addChannel(row).then((response) => {
        proxy.$modal.msgSuccess("添加成功");
        // visible.value = false;
        getList.value();
      });
      row.isAdd = false;
      getList();
    }

    if (row.isEdit) {
      updateChannel(row).then((response) => {
        proxy.$modal.msgSuccess("修改成功");
        // visible.value = false;
        getList.value();
      });
      queryParams.isEdit = false;
      getList();
    }

    getList();
  } else {
    proxy.$modal.msgError("渠道名称和负责人不能为空！");
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  row.isEdit = true;
}

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/channel/export",
    {
      ...queryParams.value,
    },
    `channel_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
