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

      <!-- <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
        v-hasPermi="['business:workOrder:remove']">删除</el-button> -->
      <el-dropdown>
        <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
              icon="Download"
              @click="handleExport"
              v-hasPermi="['business:workOrder: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"
      label-width="68px"
    >
      <el-form-item label="客户名称：" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入客户名称"
          style="width: 150px"
          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="orderList"
      size="small"
      border
      height="100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="客户名称"
        align="center"
        min-width="250"
        prop="companyName"
      />
      <el-table-column
        label="税号"
        align="center"
        min-width="180"
        prop="socialCreditCode"
      />
      <el-table-column
        label="服务内容"
        align="center"
        min-width="650"
        prop="remark"
      >
        <template #default="scope">
          <div>{{ scope.row.remark }}</div>
        </template>
      </el-table-column>
      <el-table-column label="工单执行人" align="center" width="130">
        <template #default="scope">{{ getTransactor(scope.row) }}</template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="新增工单"
      v-model="formOpen"
      width="500px"
      append-to-body
      draggable
    >
      <el-form ref="dictRef" :model="form" label-width="100" size="small">
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="客户名称：" prop="companyName">
              <el-autocomplete
                style="width: 100%"
                fit-input-width="300px"
                size="small"
                :fetch-suggestions="querySearchCompanyAsync"
                :trigger-on-focus="true"
                v-model="form.companyName"
                placeholder="请输入客户名称"
                @select="handleSelectCompany"
              >
                <template #append>
                  <el-button icon="Plus" @click="showAddCompanyDialog">
                  </el-button>
                </template>
                <template #default="{ item }">
                  <div
                    style="
                      display: flex;
                      flex-direction: row;
                      justify-content: space-between;
                    "
                  >
                    <div class="name" style="font-size: 12px">
                      {{ item.name }}
                    </div>
                    <!-- <span class="code" style="font-size: 10px; color: darkgrey;">{{ item.code }}</span> -->
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="服务内容：">
              <el-input
                v-model.trim="form.remark"
                type="textarea"
                size="small"
                :rows="4"
                maxlength="200"
                show-word-limit
                placeholder="服务内容"
                :clearable="true"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24"> </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="Finished"
            size="small"
            @click="saveHandler"
            >确 定</el-button
          >
          <el-button @click="formCancel" icon="close" size="small"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <AddCompanyDialog ref="addCompanyDialogRef" />
  </div>
</template>

<script setup name="Company">
// import contractForm from "./form";
import {
  listWorkOrder,
  delWorkOrder,
  exportWorkOrder,
  addWorkOrder,
  exportNoContract,
} from "@/api/business/crm/workOrder";
import { listCompany } from "@/api/business/crm/company";
import AddCompanyDialog from "../AddCompanyDialog.vue";
import { ref } 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 addCompanyDialogRef = ref(null);

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: "",
  noContract: 1,
};

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

const editStatus = {
  startMonth: false,
};

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

/** 查询company列表 */
function getList() {
  loading.value = true;
  listWorkOrder(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() {
  // proxy.$refs.workOrderRef.open();
  formOpen.value = true;
}

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

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

/** 修改按钮操作 */
function handleUpdate(row) {
  // const id = row.id || ids.value;
  // proxy.$refs.workOrderRef.open(id);
}

/** 删除按钮操作 */
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() {
  exportNoContract(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 querySearchCompanyAsync(queryString, cb) {
  const query =
    queryString.length > 0
      ? {
          keyword: queryString,
          pageSize: 20,
          pageNum: 1,
          orderByColumn: "create_time",
        }
      : { pageSize: 20, pageNum: 1, orderByColumn: "create_time" };
  listCompany(query).then((res) => {
    cb(res.rows);
  });
}

function handleSelectCompany(item) {
  form.value.companyName = item.name;
  form.value.companyId = item.id;
}

function saveHandler() {
  if (form.value.companyId == null) {
    proxy.$modal.msgError("请选择公司");
    return;
  }
  if (form.value.remark == null || form.value.remark === "") {
    proxy.$modal.msgError("请输入备注");
    return;
  }
  if (form.value.id == null) {
    addWorkOrder(form.value).then((res) => {
      formCancel();
      getList();
    });
  }
}

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 showAddCompanyDialog() {
  addCompanyDialogRef.value.open();
}

getList();
</script>
