<!-- 每日填写弹窗 -->
<template>
  <el-dialog
    title="服务填写"
    :visible.sync="visible"
    width="1200px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleDialogClose"
    custom-class="daily-write-dialog"
  >
    <div class="service-info">
      <div class="info-item">
        <span class="label">客户：</span>
        <span class="value">{{ rowData?.customerName || "" }}</span>
      </div>
      <div class="info-item">
        <span class="label">预计完成时间：</span>
        <span class="value">{{ rowData?.estimatedCompleteTime || "" }}</span>
      </div>
      <div class="info-item">
        <span class="label">服务人员：</span>
        <span class="value">{{ rowData?.serviceStaffNames || "" }}</span>
      </div>
    </div>

    <div class="table-header">
      <div class="date-select">
        <span class="label">日期（日期可多选，最多可选择三天）：</span>
        <el-date-picker
          v-model="selectedDates"
          type="dates"
          placeholder="选择日期（最多可选3天）"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          :style="{ width: '400px' }"
          :picker-options="{
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
          }"
          @change="handleDateChange"
        />
      </div>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-refresh-right"
        @click="resetTable"
        >重置</el-button
      >
    </div>

    <el-table :data="tableData" border style="width: 100%; margin-top: 15px">
      <el-table-column prop="date" label="日期" width="100" align="center" />
      <el-table-column
        prop="projectName"
        label="服务项目"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="primary"> {{ scope.row.projectName }} </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="goodsName" label="货品" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsName }}
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="服务人员" align="center" />
      <el-table-column prop="isWrite" label="已填写" width="80" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isWrite === '已填写' ? 'success' : 'warning'"
          >
            {{ scope.row.isWrite === "已填写" ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderQuantity" label="计划总量" align="center" />
      <el-table-column prop="installQuantity" label="已完成量" align="center" />
      <el-table-column prop="unshippedQuantity" label="剩余量" align="center" />
      <el-table-column
        prop="todayQuantity"
        label="当日完成量"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-input
            v-model.number="scope.row.todayQuantity"
            size="small"
            type="number"
            min="0"
            @input="handleTodayQuantityChange(scope.row)"
            style="width: 80px"
            placeholder="必填"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="installRemark"
        label="备注"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.installRemark"
            type="text"
            size="small"
            placeholder="请输入备注（必填）"
            maxlength="200"
            show-word-limit
            :class="{ 'is-error': scope.row.remarkError }"
            @input="handleRemarkInput(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            class="delete-btn"
            @click="handleDelete(scope.$index)"
          >
            <i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        @click="handleSubmit"
        :loading="submitting"
        class="submit-btn"
      >
        保存
      </el-button>
      <el-button @click="handleCancel" class="cancel-btn"> 取消 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  GetDataByName,
  GetDataByNames,
  PostDataByName,
  ExecDataByConfig,
} from "@/api/common";
export default {
  name: "DailyWriteDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => ({}),
    },
    currentUser: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      submitting: false,
      tableData: [],
      selectedDates: [new Date().toISOString().split("T")[0]],
      form: {
        date: new Date(),
        goods: "",
        totalQuantity: 0,
        completedQuantity: 0,
        todayQuantity: 0,
        remainingQuantity: 0,
        remark: "",
      },
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.selectedDates = [new Date().toISOString().split("T")[0]];
        this.handleDateChange(this.selectedDates);
        this.tableData = [];
      }
    },
  },
  methods: {
    // 处理日期选择变化
    async handleDateChange(dates) {
      if (!dates) {
        this.selectedDates = [];
        this.tableData = [];
        return;
      }

      // 限制最多选择3天
      if (dates.length > 3) {
        this.$message.warning("最多只能选择3天");
        this.selectedDates = dates.slice(0, 3);
        dates = this.selectedDates;
      }

      // 这里添加加载状态
      this.$set(this, "loading", true);
      console.log("选择的日期：", dates);

      // 调用后端接口获取数据
      const params = {
        name: "getInstallationDailyData",
        returntype: "Map",
        parammaps: {
          orderId: this.rowData.id,
          userId: this.currentUser.id,
          dates: dates.join(","),
        },
      };

      try {
        const response = await GetDataByName(params).catch((error) => {
          console.error("API调用出错：", error);
          throw error;
        });

        if (!response) {
          throw new Error("接口返回数据为空");
        }

        if (response.msg === "ok") {
          if (response.data.list && response.data.list.length > 0) {
            await this.initTableDataWithResponse(response.data.list);
          } else {
            console.warn("返回数据列表为空");
            this.tableData = [];
            this.$message.warning("暂无数据");
          }
        } else {
          console.error("接口返回错误：", response.msg);
          this.$message.error(response?.msg || "获取数据失败");
          this.tableData = [];
        }
      } catch (error) {
        console.error("数据处理失败:", error);
        this.$message.error(error.message || "获取数据失败");
        this.tableData = [];
      } finally {
        this.$set(this, "loading", false);
      }
    },

    // 根据返回数据初始化表格
    async initTableDataWithResponse(responseData) {
      if (!Array.isArray(responseData)) {
        console.error("返回数据格式错误:", responseData);
        this.$message.error("数据格式错误");
        return;
      }

      try {
        console.log("开始处理表格数据:", responseData);
        this.tableData = responseData.map((item) => {
          // 根据是否填写状态计算初始剩余量
          let unshippedQuantity;
          if (item.isWrite === "已填写") {
            // 如果是已填写状态，剩余量 = 计划总量 - 已完成完成量
            unshippedQuantity = Math.max(
              0,
              item.orderQuantity - item.installQuantity
            );
          } else {
            // 如果是未填写状态，剩余量 = 计划总量 - 已完成量 - 当日完成量
            unshippedQuantity = Math.max(
              0,
              item.orderQuantity - item.installQuantity - item.todayQuantity
            );
          }

          const processedItem = {
            date: item.date,
            goodsName: item.goodsName,
            projectName: item.projectName,
            goodsId: item.goodsId,
            orderQuantity: item.orderQuantity || 0,
            installQuantity: item.installQuantity || 0,
            todayQuantity: item.todayQuantity || 0,
            unshippedQuantity: unshippedQuantity,
            installRemark: item.installRemark || "",
            isWrite: item.isWrite || "未填写",
            orderId: item.orderId,
            userName: item.userName,
            projectId: item.projectId,
            projectName: item.projectName,
            oldTodayQuantity: item.oldTodayQuantity || 0,
            oldInstallQuantity: item.oldInstallQuantity || 0,
          };
          return processedItem;
        });
      } catch (error) {
        console.error("初始化表格数据失败:", error);
        this.$message.error("初始化数据失败");
        this.tableData = [];
      }
    },

    // 重置表格
    resetTable() {
      this.selectedDates = [];
      this.tableData = [];
    },

    // 处理今日完成量变化
    handleTodayQuantityChange(row) {
      // 确保输入的是非负整数
      row.todayQuantity = Math.floor(Math.max(0, row.todayQuantity));

      // 根据是否填写状态计算剩余量
      if (row.isWrite === "已填写") {
        row.installQuantity = row.oldInstallQuantity - row.oldTodayQuantity;
      }
      // 剩余量 = 计划总量 - 已完成量 - 当日完成量
      row.unshippedQuantity =
        row.orderQuantity - row.installQuantity - row.todayQuantity < 0
          ? 0
          : row.orderQuantity - row.installQuantity - row.todayQuantity;
    },

    // 验证表格数据
    validateTableData() {
      let isValid = true;
      const emptyRemarkRows = this.tableData.filter(
        (row) => !row.installRemark?.trim()
      );

      // 重置所有行的错误状态
      this.tableData.forEach((row) => {
        this.$set(row, "remarkError", false);
      });

      if (emptyRemarkRows.length > 0) {
        // 标记未填写备注的行
        emptyRemarkRows.forEach((row) => {
          this.$set(row, "remarkError", true);
        });

        const dates = emptyRemarkRows.map((row) => row.date).join("、");
        this.$message.error(`请填写 ${dates} 的备注信息`);
        isValid = false;
      }

      return isValid;
    },

    // 处理备注输入
    handleRemarkInput(row) {
      if (row.remarkError && row.installRemark?.trim()) {
        this.$set(row, "remarkError", false);
      }
    },

    // 删除行
    handleDelete(index) {
      this.tableData.splice(index, 1);
    },
    // 提交表单
    async handleSubmit() {
      if (!this.tableData.length) {
        this.$message.warning("请至少填写一条记录");
        return;
      }

      // 验证当日完成量
      if (!this.validateTableData()) {
        return;
      }

      this.submitting = true;
      try {
        await this.$emit("confirm", {
          records: this.tableData,
          dates: this.selectedDates,
        });
      } finally {
        this.submitting = false;
      }
    },
    // 取消
    handleCancel() {
      this.$emit("update:visible", false);
    },
    // 关闭弹窗
    handleDialogClose() {
      this.tableData = [];
      this.handleCancel();
    },
  },
};
</script>

<style lang="scss" scoped>
.daily-write-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 20px 10px 20px;
  }

  .service-info {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;

    .info-item {
      display: flex;
      align-items: center;

      .label {
        color: #606266;
        margin-right: 8px;
        font-size: 14px;
      }

      .value {
        color: #333;
        font-weight: 500;
        font-size: 14px;
      }
    }
  }

  .table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    padding: 0 5px;

    .date-select {
      display: flex;
      align-items: center;

      .label {
        margin-right: 10px;
        font-size: 14px;
        color: #606266;
      }
    }

    .el-button {
      margin-left: 15px;
    }
  }

  :deep(.el-table) {
    margin-top: 15px;

    th {
      background-color: #f5f7fa;
      color: #333;
      font-weight: 500;
      height: 44px;
      padding: 8px 0;
      text-align: center;
    }

    td {
      padding: 4px 0;
    }

    .delete-btn {
      color: #f56c6c;
      font-size: 16px;
      padding: 0;
      margin: 0;

      &:hover {
        color: #ff7875;
        transform: scale(1.1);
      }

      &:active {
        transform: scale(0.9);
      }
    }

    .el-input-number {
      width: 100px;
    }

    .el-date-editor {
      .el-input__inner {
        font-size: 12px;
        padding-left: 25px;
      }
    }

    .el-input__inner {
      text-align: center;
    }

    .el-input {
      &.is-error {
        .el-input__inner {
          border-color: #f56c6c;

          &:focus {
            border-color: #f56c6c;
            box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
          }
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 10px;

    .submit-btn {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      margin-left: 10px;
      transition: all 0.3s;

      &:hover {
        opacity: 0.8;
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .cancel-btn {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      transition: all 0.3s;
      border: 1px solid #dcdfe6;

      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
        transform: translateY(-1px);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }
}
</style>
