<template>
  <div class="page-container list-container">
    <!-- 功能按钮区 -->
    <div class="list-btns-container">
      <el-dropdown trigger="click">
        <el-button
          type="primary"
          size="small"
          v-if="
            hasPermi([
              'business:customer:service:once:export',
              'business:customer:service:once:transactor',
            ])
          "
        >
          其它<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              icon="Download"
              @click="handleExport"
              v-if="hasPermi(['business:customer:service:once:exportOnce'])"
            >
              导出</el-dropdown-item
            >
            <el-dropdown-item
              icon="Operation"
              @click="setServiceHandler"
              v-if="hasPermi(['business:customer:service:once:transactor'])"
            >
              设置执行人</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      size="small"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称：" prop="companyName">
        <el-input
          style="width: 150px"
          v-model="queryParams.companyName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model.trim="queryParams.status"
          size="small"
          type="text"
          placeholder="状态"
          :clearable="true"
          style="width: 130px"
          @clear="clearStatus"
        >
          <el-option
            v-for="item in selectStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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="orderList"
      size="small"
      border
      height="100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="工单号" align="center" prop="workOrderNo" width="200" /> -->
      <el-table-column
        label="客户名称"
        align="center"
        prop="companyName"
        min-width="250"
      />
      <!-- <el-table-column
        label="税号"
        align="center"
        prop="socialCreditCode"
        min-width="180"
      /> -->
      <el-table-column
        label="服务内容"
        align="center"
        min-width="480"
        prop="remark"
      >
        <template #default="scope">
          <div>
            {{
              scope.row.noContract === 1? scope.row.remark: `${scope.row.taskTypeName}${scope.row.alterType ?`-${scope.row.alterType}` : ""}${scope.row.taskTypeDetailName? `-${scope.row.taskTypeDetailName}` : ""}`
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="说明"
        align="center"
        prop="explain"
        min-width="180"
      />
      <el-table-column label="状态" align="center" width="80">
        <template #default="scope">
          <div :style="getStatusStyle(scope.row)">
            {{ getStatusLabel(scope.row) }}
            <el-popover placement="top-start" width="250" trigger="hover">
              <div style="display: flex; flex-direction: row">
                <div
                  v-for="item in selectStatus"
                  :key="item.value"
                  style="display: flex; flex-direction: row; margin-right: 10px"
                >
                  <div
                    :style="{
                      backgroundColor: item.color,
                      width: '14px',
                      height: '14px',
                      margin: 'auto',
                      borderRadius: '50%',
                      border: item.color === '#fff' ? '1px solid #ddd' : 'none',
                    }"
                  />
                  <div
                    style="
                      display: inline-block;
                      margin-left: 10px;
                      line-height: 36px;
                      font-size: 10px;
                    "
                  >
                    {{ item.label }}
                  </div>
                </div>
              </div>
              <template #reference>
                <span
                  style="
                    color: #fff;
                    font-size: 12px;
                    text-align: center;
                    display: inline-block;
                    line-height: 14px;
                    width: 14px;
                    height: 14px;
                    background-color: #ccc;
                    border-radius: 50%;
                  "
                  >?</span
                >
              </template>
            </el-popover>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="60">
        <template #default="scope">
          <el-button
            size="small"
            link
            type="primary"
            v-hasPermi="[
              'business:customer:service:once:view',
              'business:customer:service:once:edit',
            ]"
            @click="handleByRow(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="工单执行人" align="center" width="110">
        <template #default="scope">{{ getTransactor(scope.row) }}</template>
      </el-table-column>
      <el-table-column label="停止" align="center" prop="isStop" width="50">
        <template #default="scope">{{
          scope.row.isStop === 1 ? "是" : "否"
        }}</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"
    />
    <service-form ref="serviceRef" :get-list="getList" />
    <form-dialog ref="formRef" :get-list="getList" />
    <view-dialog ref="viewRef" :get-list="getList" />
  </div>
</template>

<script setup name="Once">
import { listOnce, exportOnce } from "@/api/business/crm/serviceWorkOrder";
import auth from "@/plugins/auth";
import useUserStore from "@/store/modules/user";
const permissions = useUserStore().permissions;
const all_permission = "*:*:*";

import formDialog from "./form";
import viewDialog from "./view";
import serviceForm from "../serviceForm";
import { ref, toRef } from "vue";
// import workorderForm from "./form"
const { proxy } = getCurrentInstance();
/** 字典数组区 */
/** 查询 对象 */

const orderList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const prev = ref([]);

const data = reactive({
  selectStatus: [
    {
      label: "未开始",
      value: 0,
      color: "#888",
    },
    {
      label: "进行中",
      value: 1,
      color: "#FFB836",
    },
    {
      label: "已完成",
      value: 3,
      color: "#2FCB81",
    },
  ],
});
const formRef = ref(null);
const viewRef = ref(null);

const { selectStatus } = toRefs(data);

const formOpen = ref(false);

const form = ref({
  id: null,
  companyName: "",
  companyId: null,
  remark: "",
  type: 2,
  noContract: 1,
});

const emptyForm = {
  id: null,
  companyName: "",
  companyId: null,
  type: 2,
  remark: "",
};

const { contract_verify_status } = proxy.useDict("contract_verify_status");
const { contract_status } = proxy.useDict("contract_status");
/** 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  companyName: "",
  orderByColumn: "create_time",
  type: 2,
});

const editStatus = {
  startMonth: false,
};

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

/** 查询company列表 */
function getList() {
  loading.value = true;
  listOnce(queryParams.value).then((response) => {
    orderList.value = response.rows.map((l) => ({
      ...l,
      editStatus: proxy.deepClone(editStatus),
    }));
    prev.value = proxy.deepClone(response.rows);
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
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() {
  formOpen.value = true;
}

function formCancel() {
  formOpen.value = false;
  reset();
}

function reset() {
  form.value = proxy.deepClone(emptyForm);
}

/** 修改按钮操作 */
function handleUpdate(row) {}

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

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

function startDateChangeHandler(row, startDate) {
  if (startDate) {
    // console.log(startDate)
    row.endMonth = proxy
      .moment(startDate)
      .add(row.monthNum - 1, "M")
      .format("YYYY-MM-DD");
  } else row.endMonth = null;
  console.log(row);
}

function saveHandler() {
  if (form.value.id == null) {
    addWorkOrder(form.value).then((res) => {
      formCancel();
      getList();
    });
  }
}

function setServiceHandler() {
  if (ids.value.length === 0) {
    proxy.$modal.msgError("请先选择需要设置的工单！");
    return;
  }
  proxy.$refs["serviceRef"].open({
    dialogTitle: "设置执行人",
    dialogContent: "请输入执行人姓名",
    values: ids.value,
  });
}

function getStatusStyle(row) {
  const record = row.records.find((v) => v.fromId === "0");
  if (record == null) {
    return { color: getStatusColor(0), verticalAlign: "middle" };
  } else {
    return { color: getStatusColor(record.status), verticalAlign: "middle" };
  }
}
function getStatusColor(status) {
  const index = selectStatus.value.findIndex((v) => v.value === status);
  return index >= 0 ? selectStatus.value[index].color : "#fff";
}
function getStatusLabel(row) {
  const record = row.records.find((v) => v.fromId === "0");
  const index = selectStatus.value.findIndex(
    (v) => v.value === (record == null ? 0 : record.status)
  );
  return index >= 0 ? selectStatus.value[index].label : "";
}

function handleByRow(row) {
  const record = row.records.find((v) => v.fromId === "0");
  const editable =
    permissions.includes(all_permission) ||
    permissions.includes("business:customer:service:loop:edit") >= 0;
  const viewable =
    permissions.includes(all_permission) ||
    permissions.includes("business:customer:service:loop:view") >= 0;

  if (record == null && row.isStop == 1) {
    proxy.$modal.msg("工单已终止");
    return;
  }

  if (
    record != null &&
    (record.status === 3 || row.isStop == 1) &&
    (editable || viewable)
  ) {
    viewRef.value.open({
      workOrderId: row.id,
      companyId: row.companyId,
      companyName: row.companyName,
    });
  } else if (
    row.entrusts != null &&
    row.entrusts.length > 0 &&
    (editable || viewable)
  ) {
    if (row.entrusts.length >= 0) {
      viewRef.value.open({
        workOrderId: row.id,
        companyId: row.companyId,
        companyName: row.companyName,
      });
    } else if (editable) {
      formRef.value.open({
        workOrderId: row.id,
        companyId: row.companyId,
        companyName: row.companyName,
      });
    } else {
      proxy.$modal.msg("没有修改权限");
    }
  } else if (editable) {
    formRef.value.open({
      workOrderId: row.id,
      companyId: row.companyId,
      companyName: row.companyName,
    });
  } else {
    proxy.$modal.msg("没有修改权限");
  }
}

function getTransactor(row) {
  if (row.entrusts != null && row.entrusts.length > 0) {
    const names = Array.from(new Set(row.entrusts.map((v) => v.toAccountName)));
    return names.join(",");
  } else {
    return row.serviceName;
  }
}

function clearStatus() {
  queryParams.value.status = null;
}

function hasPermi(arr) {
  return auth.hasPermiOr(arr);
}
getList();
</script>
