<template>
  <div class="data-info">
    <el-card>
      <el-form
        :model="dataForm"
        :rules="rules"
        ref="dataFormRef"
        label-width="120px"
      >
        <el-form-item
          label="客户名称:"
          prop="customerId"
          class="form-item-half"
        >
          <el-select
            clearable
            filterable
            v-model="dataForm.customerId"
            placeholder="请选择客户"
            size="large"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称:" prop="name" class="form-item-half">
          <el-input
            v-model="dataForm.name"
            placeholder="请输入项目名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="产品:" prop="product" class="form-item-half">
          <el-select
            clearable
            filterable
            v-model="dataForm.product"
            placeholder="请选择产品"
            size="large"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="项目分类:"
          prop="ProjectCategory"
          class="form-item-half"
        >
          <el-select
            clearable
            filterable
            v-model="dataForm.ProjectCategory"
            placeholder="请选择项目分类"
            size="large"
          >
            <el-option
              v-for="item in allCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="产品名称:"
          prop="productName"
          class="form-item-half"
        >
          <el-input
            v-model="dataForm.productName"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item> -->
        <el-form-item
          label="服务内容:"
          prop="service_content"
          class="form-item-half"
        >
          <el-input
            v-model="dataForm.service_content"
            placeholder="请输入服务内容"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="当前阶段:"
          prop="current_phase"
          class="form-item-half"
        >
          <el-select
            clearable
            filterable
            v-model="dataForm.current_phase"
            placeholder="请选择当前阶段"
            size="large"
          >
            <el-option
              v-for="item in currentPhaseList"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="目前状态:"
          prop="project_status"
          class="form-item-half"
        >
          <el-select
            clearable
            filterable
            v-model="dataForm.project_status"
            placeholder="请选择目前状态"
            size="large"
          >
            <el-option
              v-for="item in getstatusList"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="项目日期:"
          prop="start_date"
          class="form-item-half"
        >
          <el-date-picker
            clearable
            v-model="dataForm.start_date"
            type="date"
            placeholder="请选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
    </el-card>

    <div style="text-align: right; margin-top: 20px">
      <el-button type="warning" @click="btnSave">确认保存</el-button>
    </div>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import {
  searchCategory,
  createProject,
  updateProject,
  getProjectInfo,
  getphases,
  getstatus,
} from "@/api/project";
import { searchProduct } from "@/api/product";
import { searchCustomer } from "@/api/customer";
import { searchDocument } from "@/api/document";
export default {
  components: {
    Tinymce,
  },
  emits: ["onClose"],
  props: {
    id: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    id: {
      handler(v) {
        let _this = this;
        if (v == null) return;
        if (v == 0) {
          this.dataForm = {
            id: 0,
            name: "",
            intro: "",
            customerId: "",
            ProjectCategory: "",
            status: 5,
            product: "",
            service_content: "",
            current_phase: "P1", // 设置当前阶段默认值为 P1
            project_status: 1, // 设置目前状态默认值为 1
            start_date: new Date().toISOString().slice(0, 10), // 设置默认日期为今天
          };
          return;
        }
        _this.getInfo(v);
      },
      immediate: true,
      deep: true,
    },
  },
  data() {
    return {
      activeName: "base",
      currentCategory: [],
      allCategories: [],
      imageUrl: "",
      customerList: [],
      articleList: [],
      currentPhaseList: [], //阶段表
      getstatusList: [], //状态表
      productList: [], //产品列表
      dataForm: {
        id: 0,
        name: "",
        intro: "",
        customerId: "",
        ProjectCategory: "", //测试
        status: 5,
        product: "", // 新增产品类别
        //productName: "", // 新增产品名称
        service_content: "", // 新增服务内容
        current_phase: "P1", // 设置当前阶段默认值为 P1
        project_status: "1", // 设置目前状态默认值为 1
        start_date: new Date().toISOString().slice(0, 10), // 新增项目日期
      },
      statusOptions: [
        {
          status: 5,
          name: "启用",
        },
        {
          status: 6,
          name: "停用",
        },
      ],
      // 更新校验规则
      rules: {
        name: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符之间",
            trigger: "blur",
          },
        ],
        customerId: [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        /*product: [{ required: true, message: "请选择产品", trigger: "change" }],
         productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符之间",
            trigger: "blur",
          },
        ], */
        service_content: [
          { required: true, message: "请输入服务内容", trigger: "blur" },
          {
            min: 1,
            max: 200,
            message: "长度在 1 到 200 个字符之间",
            trigger: "blur",
          },
        ],
        current_phase: [
          { required: true, message: "请选择当前阶段", trigger: "change" },
        ],
        project_status: [
          { required: true, message: "请选择项目状态", trigger: "change" },
        ],
        start_date: [
          { required: true, message: "请选择项目日期", trigger: "change" },
        ],
      },
    };
  },

  mounted() {
    let _this = this;
    _this.uploadUrl = process.env.VUE_APP_BASE_API + "/upload";
    _this.initAllCategory();
    this.initCustomer();
    /*  this.initDocList(); */
  },
  methods: {
    initDocList() {
      let _this = this;
      searchDocument({
        page: 1,
        pageSize: 10,
      }).then((res) => {
        if (res.status != 200) return;
        _this.articleList = res.data.dataList;
      });
    },
    //图片上传成功
    onUploadSuccess(e) {
      console.log("onUploadSuccess", e);
    },
    //保存更新
    btnSave(e) {
      let _this = this;

      _this.$refs.dataFormRef.validate((valid) => {
        if (!valid) {
          return false;
        }

        const savePromise =
          _this.dataForm.id > 0
            ? updateProject(_this.dataForm)
            : createProject(_this.dataForm);

        savePromise
          .then((res) => {
            if (res.status !== 200) return;
            _this.$message.success(
              _this.dataForm.id > 0 ? "项目信息更新成功" : "项目信息创建成功"
            );
            setTimeout(() => {
              _this.$emit("onClose", true);
            }, 0);
          })
          .catch((error) => {
            console.error("Save failed:", error);
          });
      });
    },

    //产品详情
    getInfo(id) {
      const par = { id };
      getProjectInfo(par)
        .then((res) => {
          if (!res || res.status !== 200) return;

          const { data } = res;
          this.dataForm = {
            ...data,
            ProjectCategory: data?.ProjectCategory?.id ?? "",
            customerId: data?.customerId ?? "",
            product: data?.productId ?? "",
          };
        })
        .catch((error) => {
          console.error("获取项目信息失败:", error);
          this.$message.error("获取项目信息失败");
        });
    },

    onChangeStatus(e) {
      this.dataForm.status = e;
    },
    //修改分类信息
    onChangeCategory(e) {
      let _this = this;
      _this.dataForm.categoryId = e;
    },
    //初始化所有分类
    initAllCategory() {
      let _this = this;
      let par = {
        page: 1,
        pageSize: 9999,
        status: 5,
      };
      searchCategory(par).then((res) => {
        _this.allCategories = res.data.dataList;
      });
    },
    initCustomer() {
      let _this = this;
      let par = {
        page: 1,
        pageSize: 99,
      };
      searchCustomer(par).then((res) => {
        _this.customerList = res.data.dataList;
      });
      getphases().then((res) => {
        _this.currentPhaseList = res.data.options;
      });
      getstatus().then((res) => {
        _this.getstatusList = res.data.options;
      });
      /* 获取产品列表 */
      searchProduct({ page: 1, pageSize: 999 }).then((res) => {
        _this.productList = res.data.dataList;
        console.log(res.data.dataList);
      });
    },
  },
};
</script>

<style lang="scss">
@import "./dataInfo.scss";
.data-info {
  // 添加半宽表单项的样式
  .form-item-half {
    width: 50%;

    // 确保 select 和 input 占满容器宽度
    .el-input,
    .el-select {
      width: 100%;
    }
  }

  // 可选：添加一些响应式布局
  @media screen and (max-width: 768px) {
    .form-item-half {
      width: 100%;
    }
  }
}
</style>
