<!-- 新增服务计划弹窗 -->
<template>
  <el-dialog
    title="新增服务计划"
    :visible.sync="visible"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleDialogClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="下单人" prop="orderer">
            <el-select
              v-model="form.orderer"
              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-col>
        <el-col :span="8">
          <el-form-item label="服务人员" prop="serviceStaff">
            <el-select
              v-model="form.serviceStaff"
              multiple
              clearable
              filterable
              placeholder="请选择服务人员"
              style="width: 100%"
            >
              <el-option
                v-for="item in installerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计完成时间" prop="estimatedCompleteTime">
            <el-date-picker
              v-model="form.estimatedCompleteTime"
              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-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="发货单号" prop="deliveryNo">
            <el-input v-model="form.deliveryNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同" prop="contract">
            <el-input v-model="form.contract" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="客户" prop="customer">
            <el-select
              v-model="form.customer"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入客户名称搜索"
              :loading="loading"
              style="width: 400px !important"
              :remote-method="handleCustomerInput"
            >
              <el-option
                v-for="item in customerOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="form.remark"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>

      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item label="选择货品">
            <el-select
              v-model="selectedProduct"
              filterable
              remote
              reserve-keyword
              placeholder="请输入货品名称搜索"
              :loading="productLoading"
              style="width: 600px !important"
              :remote-method="handleProductInput"
              @change="handleProductChange"
              @focus="handleProductInput('')"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.id"
                :value="item.id"
              >
                <template>
                  <div class="product-option">
                    <div class="option-item">
                      <span class="label">编号</span>
                      <span class="value">{{ item.goodsCode }}</span>
                    </div>
                    <div class="option-item">
                      <span class="label">名称</span>
                      <el-tooltip
                        :content="item.goodsName"
                        placement="top"
                        :disabled="item.goodsName.length <= 10"
                        effect="light"
                      >
                        <span class="value">{{ item.goodsName }}</span>
                      </el-tooltip>
                    </div>
                    <div class="option-item">
                      <span class="label">规格</span>
                      <el-tooltip
                        :content="item.goodsSpecification"
                        placement="top"
                        :disabled="
                          !item.goodsSpecification ||
                          item.goodsSpecification.length <= 5
                        "
                        effect="light"
                      >
                        <span class="value">{{
                          item.goodsSpecification || "-"
                        }}</span>
                      </el-tooltip>
                    </div>
                    <!-- <div class="option-item">
                      <span class="label">型号</span>
                      <el-tooltip
                        :content="item.goodsModel"
                        placement="top"
                        :disabled="
                          !item.goodsModel || item.goodsModel.length <= 5
                        "
                        effect="light"
                      >
                        <span class="value">{{ item.goodsModel || "-" }}</span>
                      </el-tooltip>
                    </div>
                    <div class="option-item">
                      <span class="label">单位</span>
                      <span class="value">{{ item.goodsUnit || "-" }}</span>
                    </div> -->
                    <div class="option-item">
                      <span class="label">库存</span>
                      <span class="value">{{ item.stock || 0 }}</span>
                    </div>
                  </div>
                </template>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label-width="120px">
        <el-table :data="form.products" border style="width: calc(100% - 20px)">
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column label="服务项目" align="center" width="200">
            <template slot-scope="scope">
              <el-tooltip
                :content="
                  projectOptions.find((p) => p.id === scope.row.serviceProject)
                    ?.name || ''
                "
                placement="top"
                :disabled="
                  !scope.row.serviceProject ||
                  projectOptions.find((p) => p.id === scope.row.serviceProject)
                    ?.name?.length <= 8
                "
                effect="light"
              >
                <el-select
                  v-model="scope.row.serviceProject"
                  filterable
                  placeholder="请选择服务项目"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in projectOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                    <el-tooltip
                      :content="item.name"
                      placement="right"
                      :disabled="item.name.length <= 8"
                      effect="light"
                    >
                      <span class="ellipsis-text">{{ item.name }}</span>
                    </el-tooltip>
                  </el-option>
                </el-select>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsCode"
            label="货品编号"
            align="center"
            width="100"
          />
          <el-table-column
            prop="goodsName"
            label="货品名称"
            align="center"
            width="150"
          />
          <el-table-column
            prop="goodsSpecification"
            label="货品规格"
            align="center"
            width="100"
          />
          <el-table-column
            prop="stock"
            label="现有库存"
            align="center"
            width="60"
          />
          <el-table-column
            prop="orderQuantity"
            label="订单数量"
            align="center"
            width="110"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.orderQuantity"
                size="mini"
                style="width: 70px"
                @input="handleOrderQuantityInput($event, scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsImagePath"
            label="货品图片"
            align="center"
          >
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.goodsImagePath"
                :src="baseApi + scope.row.goodsImagePath"
                style="width: 50px; height: 50px"
                :preview-src-list="[baseApi + scope.row.goodsImagePath]"
                fit="contain"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
              <div
                v-else
                class="image-slot"
                style="
                  width: 50px;
                  height: 50px;
                  display: inline-flex;
                  justify-content: center;
                  align-items: center;
                  background: #f5f7fa;
                  border-radius: 4px;
                "
              >
                <i
                  class="el-icon-picture-outline"
                  style="font-size: 20px; color: #909399"
                ></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="goodsUnit"
            label="计量单位"
            align="center"
            width="50"
          />

          <el-table-column
            prop="shippedQuantity"
            label="已服务数量"
            align="center"
            width="70"
          />
          <el-table-column
            prop="unshippedQuantity"
            label="未服务数量"
            align="center"
            width="70"
          />
          <el-table-column
            prop="remark"
            label="备注"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark"
                size="mini"
                placeholder="备注"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                plain
                @click="handleRemoveProduct(scope.$index)"
                style="padding: 4px 8px; border-radius: 4px"
              >
                <i class="el-icon-delete" style="margin-right: 2px" />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </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 {
  GetDataByName,
  GetDataByNames,
  ExecDataByConfig,
  handleWechatPushOfOrder,
} from "@/api/common";
import Cookies from "js-cookie";

export default {
  name: "AddDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    installerOptions: {
      type: Array,
      default: () => [],
    },
    projectOptions: {
      type: Array,
      default: () => [],
    },
    currentUser: {
      type: Object,
      default: () => ({
        id: "",
        name: "",
      }),
    },
  },
  computed: {
    baseApi() {
      return process.env.VUE_APP_BASE_API;
    },
  },
  watch: {
    visible(val) {
      if (val) {
        // 弹窗打开时设置默认值并获取数据
        this.$nextTick(() => {
          this.form.orderer = parseInt(this.currentUser.id);
          this.customerOptions = [];
          this.getInitialData();
        });
      }
    },
  },
  data() {
    return {
      form: {
        orderer: "",
        serviceStaff: [],
        estimatedCompleteTime: "",
        deliveryNo: "",
        contract: "",
        customer: "",
        remark: "",
        products: [],
      },

      customerOptions: [], // 客户选项
      loading: false, // 客户加载状态
      selectedProduct: "", // 当前选中的货品
      productOptions: [], // 货品选项
      productLoading: false, // 货品加载状态

      // 表单校验规则
      rules: {
        orderer: [
          { required: true, message: "请选择下单人", trigger: "change" },
        ],
        serviceStaff: [
          { required: true, message: "请选择服务人员", trigger: "change" },
        ],
        // estimatedCompleteTime: [
        //   { required: true, message: "请选择预计完成时间", trigger: "change" },
        // ],
        customer: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 处理客户输入
    handleCustomerInput(value) {
      if (!value) {
        this.customerOptions = [];
        return;
      }
      this.loading = true;
      const send_select_list = {
        name: "getCustomerNameFuzzy",
        returntype: "Map",
        parammaps: {
          inputvalue: value || "",
        },
      };

      GetDataByName(send_select_list)
        .then((response) => {
          this.customerOptions = response.data.list || [];
        })
        .catch((error) => {
          console.error("搜索客户失败:", error);
          this.$message.error("搜索客户失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 关闭弹窗
    handleDialogClose() {
      this.$emit("update:visible", false);
      this.$refs.form && this.$refs.form.resetFields();
    },

    // 取消
    handleCancel() {
      this.handleDialogClose();
    },
    getInitialData() {
      this.form.products = [];
      //this.handleProductInput('')
    },
    // 移除货品
    handleRemoveProduct(index) {
      this.form.products.splice(index, 1);
    },

    // 处理货品输入搜索
    handleProductInput(value) {
      this.productLoading = true;
      const send_select_list = {
        name: "getGoodsListByCode",
        returntype: "Map",
        parammaps: {
          goodsCode: value || "",
        },
      };

      GetDataByName(send_select_list)
        .then((response) => {
          this.productOptions = response.data.list || [];
          // 打印第一条数据查看结构
          if (this.productOptions.length > 0) {
            console.log("商品数据结构:", this.productOptions[0]);
          }
        })
        .catch((error) => {
          console.error("搜索货品失败:", error);
          this.$message.error("搜索货品失败");
        })
        .finally(() => {
          this.productLoading = false;
        });
    },

    // 处理货品选择变化
    handleProductChange(value) {
      const selectedProduct = this.productOptions.find(
        (item) => item.goodsId === value
      );
      if (selectedProduct) {
        // 检查是否已经添加过该货品
        // const existingProduct = this.form.products.find(
        //   (item) => item.goodsId === selectedProduct.goodsId
        // );
        // if (existingProduct) {
        //   this.$message.warning("该货品已经添加过了");
        //   this.selectedProduct = "";
        //   return;
        // }

        // 添加新货品到表格
        this.form.products.push({
          goodsId: selectedProduct.goodsId,
          goodsCode: selectedProduct.goodsCode,
          goodsName: selectedProduct.goodsName,
          goodsSpecification: selectedProduct.goodsSpecification,
          goodsImagePath: selectedProduct.goodsImagePath || "",
          goodsUnit: selectedProduct.goodsUnit,
          stock: selectedProduct.stock || 0,
          orderQuantity: "",
          shippedQuantity: 0,
          unshippedQuantity: 0,
          remark: "",
          serviceProject: "", // 新增服务项目字段
        });
      }
      this.selectedProduct = ""; // 清空选择
    },

    // 处理订单数量输入
    handleOrderQuantityInput(value, row) {
      // 只允许输入正整数
      value = value.replace(/[^\d]/g, "");
      if (value === "") {
        row.orderQuantity = "";
      } else {
        const num = parseInt(value);
        row.orderQuantity = num || "";
      }
    },

    // 提交表单
    async handleSubmit() {
      this.$refs.form.validate(async (valid, errorFields) => {
        if (valid) {
          try {
            // 检查是否添加了货品
            if (this.form.products.length === 0) {
              this.$message.warning("请至少添加一个货品");
              return;
            }

            // 检查每个货品的必填项
            const invalidProducts = this.form.products.filter(
              (item) =>
                !item.orderQuantity ||
                parseInt(item.orderQuantity) <= 0 ||
                !item.serviceProject
            );

            if (invalidProducts.length > 0) {
              this.$message.warning(
                "请确保所有货品都已填写服务项目和订单数量（且数量大于0）"
              );
              return;
            }

            // 检查服务项目+货品名称的唯一性
            const duplicateCheck = new Map();
            const duplicateItems = [];

            this.form.products.forEach((item) => {
              const key = `${item.serviceProject}_${item.goodsName}`;
              if (duplicateCheck.has(key)) {
                duplicateItems.push({
                  goodsName: item.goodsName,
                  projectName:
                    this.projectOptions.find(
                      (p) => p.id === item.serviceProject
                    )?.name || "",
                });
              } else {
                duplicateCheck.set(key, true);
              }
            });

            if (duplicateItems.length > 0) {
              const duplicateInfo = duplicateItems
                .map((item) => `【${item.projectName} - ${item.goodsName}】`)
                .join("、");
              this.$message.warning(
                `以下服务项目和货品组合重复，请检查：${duplicateInfo}`
              );
              return;
            }

            // 构建保存参数
            const params = {
              common: {
                returnmap: "0",
              },
              data: [
                {
                  name: "insertInstallationOrder",
                  type: "e",
                  parammaps: {
                    customerId: this.form.customer,
                    customerName:
                      this.customerOptions.find(
                        (item) => item.id === this.form.customer
                      )?.name || "",
                    totalQuantity: this.form.products.reduce(
                      (sum, item) => sum + parseInt(item.orderQuantity || 0),
                      0
                    ),
                    installedQuantity: 0,
                    uninstalledQuantity: this.form.products.reduce(
                      (sum, item) => sum + parseInt(item.orderQuantity || 0),
                      0
                    ),
                    createId: this.form.orderer,
                    createName:
                      this.installerOptions.find(
                        (item) => item.value === this.form.orderer
                      )?.label || "",
                    dispatcherId: this.form.orderer,
                    dispatcherName:
                      this.installerOptions.find(
                        (item) => item.value === this.form.orderer
                      )?.label || "",
                    serviceStaffNames: this.installerOptions
                      .filter((item) =>
                        this.form.serviceStaff.includes(item.value)
                      )
                      .map((item) => item.label)
                      .join(","),
                    serviceStaffIds: this.form.serviceStaff.join(","),
                    estimatedCompleteTime:
                      this.form.estimatedCompleteTime || "",
                    remark: this.form.remark || "",
                  },
                },
                {
                  name: "insertInstallationOrderDetail",
                  resultmaps: {
                    list: this.form.products.map((item) => ({
                      projectId: item.serviceProject,
                      goodsId: item.goodsId,
                      goodsName: item.goodsName,
                      orderQuantity: parseInt(item.orderQuantity || 0),
                      shippedQuantity: 0,
                      unshippedQuantity: parseInt(item.orderQuantity || 0),
                      remark: item.remark || "",
                    })),
                  },
                  children: [
                    {
                      name: "insertInstallationOrderDetail",
                      type: "e",
                      parammaps: {
                        goodsId: "@insertInstallationOrderDetail.goodsId",
                        projectId: "@insertInstallationOrderDetail.projectId",
                        goodsName: "@insertInstallationOrderDetail.goodsName",
                        orderQuantity:
                          "@insertInstallationOrderDetail.orderQuantity",
                        remark: "@insertInstallationOrderDetail.remark",
                        shippedQuantity:
                          "@insertInstallationOrderDetail.shippedQuantity",
                        unshippedQuantity:
                          "@insertInstallationOrderDetail.unshippedQuantity",
                        orderId: "@insertInstallationOrder.LastInsertId",
                      },
                    },
                  ],
                },
                {
                  name: "insertInstallationOrderProcessLog",
                  type: "e",
                  parammaps: {
                    orderId: "@insertInstallationOrder.LastInsertId",
                    operationType: "create",
                    operationUserId: this.form.orderer,
                    operationUserName:
                      this.installerOptions.find(
                        (item) => item.value === this.form.orderer
                      )?.label || "",
                    beforeStatus: "未接单",
                    afterStatus: "未接单",
                    operationContent: "创建服务工单",
                  },
                },
              ],
            };

            // 调用保存接口
            ExecDataByConfig(params)
              .then((response) => {
                console.log("response", response);
                if (response.msg === "ok") {
                  this.$message.success("保存成功");
                  this.handleDialogClose();
                  this.$emit("success");

                  var rowId = response.data[0].resultmaps.LastInsertId;

                  var send_weixin_data1 = {
                    name: "getRemindData",
                    parammaps: {
                      userId: Cookies.get("g_userId"),
                      remindId: 76,
                      remindTypeName: "服务工单",
                      rowId: rowId,
                    },
                  };

                  handleWechatPushOfOrder(send_weixin_data1, 76).catch(
                    (error) => {
                      console.error("微信推送失败:", error);
                    }
                  );
                } else {
                  this.$message.error(response.data || "保存失败");
                }
              })
              .catch((error) => {
                console.error("保存失败:", error);
                this.$message.error("保存失败");
              });
          } catch (error) {
            console.error("保存失败:", error);
            this.$message.error("保存失败");
          }
        } else {
          // 收集并显示验证错误信息
          const errorMessages = [];
          for (const field in errorFields) {
            const errors = errorFields[field];
            errors.forEach((error) => {
              errorMessages.push(error.message);
            });
          }
          this.$message.error(`表单验证失败：${errorMessages.join("、")}`);
          return false;
        }
      });
    },
  },
};
</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-textarea {
        width: 100%;
      }

      .el-table {
        margin-top: 8px;

        th {
          background-color: #f5f7fa;
          color: #333;
          font-weight: 500;
          padding: 8px 0;
        }

        td {
          padding: 8px 0;
        }
      }
    }
  }

  .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;
      }
    }
  }
}

.product-option {
  display: flex;
  align-items: center;
  padding: 6px 12px;
  transition: all 0.25s ease;
  border-radius: 4px;
  margin: 1px;
  position: relative;
  border: 1px solid transparent;
  min-height: 32px;
  box-sizing: border-box;
  z-index: 1;

  &:hover {
    background-color: #f9fafc;
    border-color: #e4e7ed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
    z-index: 2;
  }

  .option-item {
    display: flex;
    align-items: center;
    position: relative;
    padding: 0 4px;
    box-sizing: border-box;

    &:not(:last-child) {
      padding-right: 16px;
      margin-right: 4px;

      &::after {
        content: "";
        position: absolute;
        right: 0;
        top: 50%;
        height: 14px;
        width: 1px;
        background-color: #dcdfe6;
        transform: translateY(-50%);
      }
    }

    &:nth-child(1) {
      width: 120px;
    } // 编号
    &:nth-child(2) {
      width: 250px;
    } // 名称
    &:nth-child(3) {
      width: 120px;
    } // 规格
    &:nth-child(4) {
      width: 120px;
    } // 型号
    &:nth-child(5) {
      width: 80px;
    } // 单位
    &:nth-child(6) {
      width: 80px;
    } // 库存

    .label {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      color: #409eff;
      background: rgba(64, 158, 255, 0.08);
      padding: 1px 6px;
      border-radius: 3px;
      margin-right: 6px;
      font-size: 12px;
      min-width: 32px;
      height: 18px;
      border: 1px solid rgba(64, 158, 255, 0.2);
      user-select: none;
      white-space: nowrap;
    }

    .value {
      color: #606266;
      font-size: 12px;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.2;
      padding: 0 2px;
      min-width: 0;
    }
  }
}

:deep(.el-select-dropdown__item) {
  padding: 0 8px !important;
  height: 34px !important;
  line-height: 34px !important;
  font-size: 12px; // 设置下拉选项字体大小
}

:deep(.el-select-dropdown) {
  .el-select-dropdown__item {
    font-size: 12px; // 确保下拉选项字体大小一致
  }
}

.ellipsis-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 12px; // 设置省略文本字体大小
}

:deep(.el-select) {
  .el-input__inner {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 12px; // 设置输入框字体大小
  }
}
</style>
