<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="customerName">
        <el-select
          v-model="queryParams.customerName"
          placeholder="请选择客户名称"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="option in customerOptions.customerName"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-input
          v-model="queryParams.createTime"
          placeholder="请输入创建时间"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经办人" prop="handler">
        <el-input
          v-model="queryParams.handler"
          placeholder="请输入经办人"
          clearable
          style="width: 240px"
          @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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['order:intention:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="View"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:intention:edit']"
          >查看</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:intention:remove']"
          >取消</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="intentionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template #default="props">
          <div style="padding: 20px; border-left: 4px solid #409eff">
            <p style="margin-top: 0; margin-bottom: 10px; font-weight: bold">
              订单整体作业计划:
            </p>
            <ul style="list-style: none; padding: 0; margin: 0">
              <li
                v-for="(item, index) in props.row.workPlan"
                :key="index"
                style="margin-bottom: 10px"
              >
                <span
                  :style="{
                    fontWeight: 'bold',
                    marginRight: '5px',
                    color: isPastDate(item.date) ? '#409eff' : 'inherit',
                  }"
                >
                  {{ index + 1 }}、{{ item.date }}:
                </span>
                <span
                  :style="{
                    color: isPastDate(item.date) ? '#409eff' : 'inherit',
                  }"
                >
                  {{ item.description }}
                </span>
              </li>
            </ul>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单商机名称" align="center" prop="orderName" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="类型" align="center" prop="type" />
      <el-table-column
        label="计划交付时间"
        align="center"
        prop="deliveryTime"
        width="180"
      />
      <el-table-column label="当前状态" align="center" prop="currentStatus" />
      <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"
      >
        <template #default="scope">
          <el-button
            type="text"
            icon="View"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:intention:edit']"
            >查看</el-button
          >
          <el-button
            type="text"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:intention:remove']"
            >取消</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"
    />

    <!-- 添加或查看意向订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="intentionRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="意向产品" prop="product">
          <el-input v-model="form.product" placeholder="请输入意向产品" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </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="Intention">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { parseTime } from "@/utils/ruoyi";
import { useRouter, useRoute } from "vue-router";
import { mockData } from "@/mockData";
import { statusOptions } from "@/data/commonMockData";
import { customerOptions } from "@/data/stepMockData";

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 意向订单表格数据
const intentionList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);

const router = useRouter();
const route = useRoute();

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  customerName: undefined,
  createTime: undefined,
  handler: undefined,
});

/** 查询意向订单列表 */
function getList() {
  loading.value = true;
  // 模拟后端分页
  const start = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const end = start + queryParams.value.pageSize;
  const filteredData = mockData.value.filter((item) => {
    if (
      queryParams.value.createTime &&
      !item.createTime.includes(queryParams.value.createTime)
    )
      return false;
    if (
      queryParams.value.handler &&
      !item.handler.includes(queryParams.value.handler)
    )
      return false;
    if (
      queryParams.value.customerName &&
      item.customerName !== queryParams.value.customerName
    )
      return false;
    return true;
  });
  intentionList.value = [];
  intentionList.value = filteredData.slice(start, end);
  total.value = filteredData.length;
  loading.value = false;
}

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

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    customerName: undefined,
    createTime: undefined,
    handler: undefined,
  };
  handleQuery();
}

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

/** 新增按钮操作 */
function handleAdd() {
  // form.value = {
  //   status: "0"
  // }
  // open.value = true
  // title.value = "添加意向订单"
  router.push("/order/create");
}

/** 查看按钮操作 */
function handleUpdate(row) {
  const id = row.id || ids.value[0];
  // const intention = mockData.value.find(item => item.id === id)
  // if (intention) {
  //   form.value = { ...intention }
  //   open.value = true
  //   title.value = "查看意向订单"
  // }
  router.push({ path: "/order/create", query: { id: id } });
}

/** 提交按钮 */
// function submitForm() {
//   this.$refs["intentionRef"].validate(valid => {
//     if (valid) {
//       if (form.value.id != null) {
//         // Edit operation
//         const index = mockData.value.findIndex(item => item.id === form.value.id);
//         if (index !== -1) {
//           mockData.value[index] = { ...form.value };
//           ElMessage.success("查看成功");
//         }
//       } else {
//         // Add operation
//         // Generate a simple unique ID (for static example purposes)
//         const newId = mockData.value.length > 0 ? Math.max(...mockData.value.map(item => item.id)) + 1 : 1;
//         mockData.value.push({ ...form.value, id: newId });
//         ElMessage.success("新增成功");
//       }
//       open.value = false;
//       getList();
//     }
//   });
// }

/** 取消按钮操作 */
function handleDelete(row) {
  const intentionType = row.type;
  ElMessageBox.confirm("是否确认取消当前" + intentionType + "?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 模拟取消
      mockData.value = mockData.value.filter(
        (item) => !intentionIds.includes(item.id)
      );
      ids.value = []; // Clear selection after deletion
      single.value = true;
      multiple.value = true;
      ElMessage.success("取消成功");
      getList();
    })
    .catch(() => {}); // Catch cancel to avoid console error
}

/** 取消按钮 */
// function cancel() {
//   open.value = false
//   reset()
// }

/** 表单重置 */
// function reset() {
//   form.value = {
//     status: "0"
//   }
// }

// Add isPastDate function
function isPastDate(dateStr) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const itemDate = new Date(dateStr);
  itemDate.setHours(0, 0, 0, 0);
  return itemDate <= today;
}

onMounted(() => {
  getList();
});

// Watch for route changes to refresh list
watch(
  () => route.path,
  (newPath) => {
    if (newPath === "/order/intention") {
      getList();
    }
  }
);
</script> 