<template>
  <!-- 工程管理 新增、编辑 表单组件 -->
  <div>
    <el-form
      v-loading="open"
      label-width="100px"
      size="medium"
      ref="projectParamsRef"
      :model="projectParams"
      :rules="projectParamsRules"
    >
      <el-row type="flex" justify="space-between" :gutter="24">
        <el-col :span="12">
          <el-form-item label="项目部" prop="departId">
            <el-select
              v-model="projectParams.departId"
              clearable
              filterable
              placeholder="请选择"
              @change="departChange"
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in departRange"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              <template
                  v-if="item.label.length > maxlength">
                  <el-tooltip
                    class="item-tooltip"
                    effect="dark"
                    :content="item.label"
                    placement="top"
                  >
                    <span class="ellipsis">{{ item.label }}</span>
                   </el-tooltip>
                  
              </template>
            </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工程名称" prop="proId">
            <el-select
              v-model="projectParams.proId"
              clearable
              filterable
              placeholder="请选择"
              @change="projChange"
            >
              <el-option
                v-for="item in projRange"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-between" :gutter="24">
        <el-col :span="12">
          <el-form-item label="申请人" prop="relUser">
            <el-input :maxlength="50" v-model="projectParams.relUser" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="relPhone">
            <el-input
              v-model="projectParams.relPhone"
              :maxlength="11"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <TableModel
      :columnsList="columnsListInsert"
      ref="tableRef"
      @transIdList="getIdList"
      :show-btn-crews="false"
      :show-right-tools="false"
      :show-sel="false"
      :show-index="false"
      style="margin-bottom: 100px"
    >
      <template slot="btn" slot-scope="{ queryParams }">
        <el-button
          type="primary"
          @click="handleAddEdge()"
          icon="el-icon-plus"
          size="mini"
          >添加边代设备</el-button
        >
      </template>
      <template slot="handle" slot-scope="{ data }">
        <el-button type="danger" size="mini" @click="handleDeleteEdge(data)"
          >删除</el-button
        >
      </template>
      <template slot="devName" slot-scope="{ data }">
        <el-input :maxlength="50" v-model="data.devName" placeholder="请输入"></el-input>
      </template>
      <template slot="devCode" slot-scope="{ data }">
        <el-input :maxlength="50" v-model="data.devCode" placeholder="请输入"></el-input>
      </template>
      <template slot="unitName" slot-scope="{ data }">
        <el-input :maxlength="50" v-model="data.unitName" placeholder="请输入"></el-input>
      </template>
      <template slot="areaName" slot-scope="{ data }">
        <el-input :maxlength="50" v-model="data.areaName" placeholder="请输入"></el-input>
      </template>
      <template slot="devUser" slot-scope="{ data }">
        <el-input :maxlength="50" v-model="data.devUser" placeholder="请输入"></el-input>
      </template>
      <template slot="devUserPhone" slot-scope="{ data }">
        <el-input
          v-model="data.devUserPhone"
          :maxlength="11"
          placeholder="请输入"
        ></el-input>
      </template>
    </TableModel>

    <div style="display: flex; justify-content: right">
      <el-button type="success" @click="onSubmit">确认</el-button>
      <el-button
        @click="
          () => {
            this.$emit('closeDialog');
          }
        "
        >取消</el-button
      >
    </div>
  </div>
</template>

<script>
import { columnsListInsert } from "../config-insert";
import {
  addEdgeDeviceApi,
  editEdgeDeviceApi,
  queryEdgeDeviceByIdApi,
} from "@/api/base/insert";
import { queryProjApi } from "@/api/base/crew";
import { queryProjDeptListApi } from "@/api/base/projDept";
export default {
  name: "FormProject",
  props: {
    editParams: {
      type: Object,
      default: () => null,
    },
  },
  components: {},
  created() {
    // this.getRanges();
  },
  async mounted() {
    this.open = true
    await this.getRanges();
    if (this.editParams) {
    await  Object.assign(this.projectParams, this.editParams);
      // 查询所属设备
    await  queryEdgeDeviceByIdApi(this.editParams.id)
        .then((res) => {
          res.rows.forEach((item) => {
            this.$refs.tableRef.tableList.unshift(item);
          });
          this.$refs.tableRef.total = res.rows.length;
        })
        .catch((err) => {});
      this.subSort = 2;
    } else {
      this.subSort = 1;
    }
    this.open = false
  },
  data() {
    return {
      columnsListInsert,
      open: false,
      exportList: [],
      subSort: "", // 提交类型：新增 1 / 修改 2
      projectParams: {
        departId: undefined, //项目部
        proId: undefined, //工程名称
        relUser: undefined, // 申请人
        relPhone: undefined, // 联系方式
      },
      // 校验规则
      projectParamsRules: {
        departId: [
          {
            required: true,
            message: "请输入项目部名称",
            trigger: "blur",
          },
        ],
        proId: [
          {
            required: true,
            message: "请输入工程名称",
            trigger: "blur",
          },
        ],
        relUser: [
          {
            required: true,
            message: "请输入申请人",
            trigger: "blur",
          },
        ],
        relPhone: [
          {
            required: true,
            message: "手机号格式不正确",
            validator: this.validatePhone,
            trigger: "blur",
          },
        ],
      },
      maxlength:20,
      // 各类下拉
      departRange: [],
      projRange: [],
      // 手机正则
      phoneReg: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      testId: 1,
    };
  },
  methods: {
    /** 校验手机号 */
    validatePhone(rule, value, callback) {
      if (!this.phoneReg.test(value)) {
        callback(new Error("手机号格式不正确"));
      } else {
        callback();
      }
    },
    getIdList(idList) {
      this.exportList = [];
      console.log(idList);
    },
    handleAddEdge() {
      let setObj = {};
      this.$set(setObj, "testId", this.testId);
      this.testId++;
      this.$set(setObj, "devName", undefined);
      this.$set(setObj, "devCode", undefined);
      this.$set(setObj, "unitName", undefined);
      this.$set(setObj, "areaName", undefined);
      this.$set(setObj, "devUser", undefined);
      this.$set(setObj, "devUserPhone", undefined);
      this.$refs.tableRef.tableList.push(setObj);
    },
    handleDeleteEdge(v) {
      this.$modal
        .confirm("是否确认删除该数据项？")
        .then(() => {
          this.$refs.tableRef.tableList.forEach((item, index) => {
            if (item.testId === v.testId) {
              this.$refs.tableRef.tableList.splice(index, 1);
            }
          });
        })
        .catch(() => {});
    },

    /** 获取各类下拉框 */
    async getRanges() {
      // 获取项目部下拉选
      let deptRes = await queryProjDeptListApi({
        isAll: 0,
      });
      this.departRange = deptRes.data.map((item) => {
        return {
          label: item.departName,
          value: item.id,
        };
      });

    },
    departChange(e) {
      this.departRange.forEach((item) => {
        if (e === item.value) {
          this.projectParams.departName = item.label;
          // 获取工程下拉选
          let projRes =  queryProjApi({
            isAll: 0,
            departId: e,
          }).then(projRes =>{
          this.projRange = projRes.data.map((item) => {
            return {
              label: item.proName,
              value: item.id,
            };
          });
          })
        }
      });
    },
    projChange(e) {
      this.projRange.forEach(item => {
        if (e === item.value) {
          this.projectParams.proName = item.label;
        }
      });
    },
    /** 改变树结构 */
    changeTree(leaf) {
      leaf.map((item) => {
        item.value = item.id;
        if (item.children) {
          this.changeTree(item.children);
        }
      });
      return leaf;
    },
    /** 确认按钮 */
    onSubmit() {
      console.log(this.$refs.tableRef.tableList, this.projectParams);
      this.$refs.projectParamsRef.validate(async (valid) => {
        if (valid) {
          this.projectParams.recordList = this.$refs.tableRef.tableList;
          if (this.subSort === 1) {
            let res = await addEdgeDeviceApi(this.projectParams);
            if (res.code === 200) {
              this.$modal.msgSuccess("操作成功");
              this.$emit("closeDialog", true);
            }
          } else {
            let res = await editEdgeDeviceApi(this.projectParams);
            if (res.code === 200) {
              this.$modal.msgSuccess("操作成功");
              this.$emit("closeDialog", true);
            }
          }
        }
      });
    },
  },
};
</script>

<style scoped>

.ellipsis {
  display: block; /* 确保是块级元素 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏超出的部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  max-width: 400px; /* 设置最大宽度，调整为你需要的值 */
}

::v-deep .el-select {
  width: 100%;
}
::v-deep .el-form-item__label {
  font-weight: normal;
}
</style>
