<!-- 派单弹窗 -->
<template>
  <el-dialog
    title="派单"
    :visible.sync="visible"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleDialogClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="服务人员" prop="serviceStaffIds">
        <el-select
          v-model="form.serviceStaffIds"
          multiple
          placeholder="请选择服务人员"
          style="width: 100%"
          filterable
          @change="handleServiceStaffChange"
        >
          <el-option
            v-for="item in installerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="派单人" prop="dispatcherId">
        <el-select
          v-model="form.dispatcherId"
          placeholder="请选择派单人"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in installerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="派单日期" prop="dispatcherDate">
        <el-date-picker
          v-model="form.dispatcherDate"
          disabled
          type="date"
          placeholder="选择派单日期"
          style="width: 100%"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          clearable
          :picker-options="{
            disabledDate: (time) => {
              const todayStart = new Date();
              todayStart.setHours(0, 0, 0, 0); // 获取当天 00:00:00.000
              return time.getTime() < todayStart.getTime();
            },
          }"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  ExecDataByConfig,
  GetDataByName,
  handleWechatPushOfOrder,
} from "@/api/common";
import Cookies from "js-cookie";
export default {
  name: "DispatchDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    installerOptions: {
      type: Array,
      default: () => [],
    },
    currentUser: {
      type: Object,
      default: () => ({
        id: "",
        name: "",
      }),
    },
    rowData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {
        serviceStaffIds: [],
        dispatcherId: "",
        dispatcherDate: this.formatDate(new Date()),
      },
      previousServiceStaffIds: [],
      rules: {
        serviceStaffIds: [
          { required: true, message: "请选择服务人员", trigger: "change" },
        ],
        dispatcherId: [
          { required: true, message: "请选择派单人", trigger: "change" },
        ],
        dispatcherDate: [
          { required: true, message: "请选择派单日期", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    visible(val) {
      if (val) {
        // 弹窗打开时设置默认值
        this.$nextTick(() => {
          this.form.dispatcherId = parseInt(this.currentUser.id);
          this.form.dispatcherDate = this.formatDate(new Date());
          // 设置默认选中的服务人员
          if (this.rowData.serviceStaffIds) {
            this.form.serviceStaffIds = this.rowData.serviceStaffIds
              .split(",")
              .map((id) => parseInt(id.trim()));
            this.previousServiceStaffIds = [...this.form.serviceStaffIds]; // 保存初始状态
          }
        });
      }
    },
  },
  methods: {
    // 处理服务人员选择变化
    async handleServiceStaffChange(newValue) {
      // 找出被删除的 ID（只会有一个）
      const removedId = this.previousServiceStaffIds.find(
        (id) => !newValue.includes(id)
      );

      // 如果有被删除的 ID
      if (removedId) {
        // 获取被删除人员的名称
        const removedStaff = this.installerOptions.find(
          (item) => item.value === removedId
        );

        const params = {
          name: "checkIsDoOrderByUserId",
          returntype: "Map",
          parammaps: {
            orderId: this.rowData.id,
            userId: removedId,
          },
        };

        try {
          const response = await GetDataByName(params);
          if (!response) {
            throw new Error("接口返回数据为空");
          }
          if (response.data.list && response.data.list[0].result === "1") {
            this.$message.warning(
              `不能移除， ${removedStaff?.label || "当前服务人员"} 已开始服务`
            );
            // 恢复选中状态
            this.$nextTick(() => {
              this.form.serviceStaffIds = [...this.previousServiceStaffIds];
            });
            return;
          }
        } catch (error) {
          console.error("数据处理失败:", error);
        }
      }

      // 如果检查通过，更新上一次的选择状态
      this.previousServiceStaffIds = [...newValue];
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$emit("update:visible", false);
      this.$refs.form && this.$refs.form.resetFields();
      // 重置表单数据
      this.form = {
        serviceStaffIds: [],
        dispatcherId: "",
        dispatcherDate: this.formatDate(new Date()),
      };
      this.previousServiceStaffIds = []; // 重置上一次的选择状态
    },

    // 取消
    handleCancel() {
      this.handleDialogClose();
    },

    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        var dispatcherId = this.form.dispatcherId;
        if (valid) {
          try {
            const params = {
              common: {
                returnmap: "0",
              },
              data: [
                {
                  name: "dispatchInstallationOrder",
                  type: "e",
                  parammaps: {
                    orderId: this.rowData.id,
                    serviceStaffIds: this.form.serviceStaffIds.join(","),
                    serviceStaffNames: this.installerOptions
                      .filter((item) =>
                        this.form.serviceStaffIds.includes(item.value)
                      )
                      .map((item) => item.label)
                      .join(","),
                    dispatcherId: this.form.dispatcherId,
                    dispatcherName:
                      this.installerOptions.find(
                        (item) => item.value === this.form.dispatcherId
                      )?.label || "",
                    dispatcherDate: this.form.dispatcherDate || "",
                  },
                },
                {
                  name: "insertInstallationOrderProcessLog",
                  type: "e",
                  parammaps: {
                    orderId: this.rowData.id,
                    operationType: "dispatch",
                    operationUserId: this.currentUser.id,
                    operationUserName: this.currentUser.name,
                    beforeStatus: this.rowData.statusName,
                    afterStatus: this.rowData.statusName,
                    operationContent:
                      `派单给服务人员:` +
                      this.installerOptions
                        .filter((item) =>
                          this.form.serviceStaffIds.includes(item.value)
                        )
                        .map((item) => item.label)
                        .join(","),
                  },
                },
              ],
            };

            const response = await ExecDataByConfig(params);
            if (response.msg === "ok") {
              this.$message.success("派单成功");
              this.handleDialogClose();
              this.$emit("success");

              var send_weixin_data1 = {
                name: "getRemindData",
                parammaps: {
                  userId: dispatcherId,
                  remindId: 77,
                  remindTypeName: "服务工单",
                  rowId: this.rowData.id,
                },
              };

              handleWechatPushOfOrder(send_weixin_data1, 77).catch((error) => {
                console.error("微信推送失败:", error);
              });
            } else {
              this.$message.error(response.msg || "派单失败");
            }
          } catch (error) {
            console.error("派单失败:", error);
            this.$message.error("派单失败");
          }
        }
      });
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  border-radius: 8px;

  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #ebeef5;
    margin-right: 0;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }

  .el-dialog__body {
    padding: 20px;

    .el-form {
      .el-form-item {
        margin-bottom: 18px;

        .el-form-item__label {
          font-weight: normal;
          color: #606266;
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
    text-align: right;

    .el-button {
      padding: 9px 20px;
      font-size: 13px;
      border-radius: 4px;

      & + .el-button {
        margin-left: 10px;
      }
    }
  }
}
</style>
