<template>
  <el-dialog
    :title="isEdit ? '编辑施工队伍' : '新增施工队伍'"
    :visible.sync="visible"
    width="900px"
    append-to-body
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="区县公司" prop="countyOrgNm">
            <el-input v-model="form.countyOrgNm" placeholder="请输入区县公司" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="队伍名称" prop="teamNm">
            <el-input v-model="form.teamNm" placeholder="请输入队伍名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="法人代表" prop="legalPerson">
            <el-input
              v-model="form.legalPerson"
              placeholder="请输入法人代表姓名"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人联系电话" prop="legalContactPhone">
            <el-input
              v-model="form.legalContactPhone"
              placeholder="请输入法人联系电话"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="施工小组序号" prop="teamSerialNo">
            <el-input-number
              v-model="form.teamSerialNo"
              :min="1"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小组负责人" prop="teamLeader">
            <el-input
              v-model="form.teamLeader"
              placeholder="请输入小组负责人姓名"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责人电话" prop="teamLeaderPhone">
            <el-input
              v-model="form.teamLeaderPhone"
              placeholder="请输入负责人电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="作业车牌号" prop="construcCarNumber">
            <el-tag
              v-for="tag in form.construcCarNumber"
              :key="tag"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
              style="margin-right: 10px; margin-bottom: 10px"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
            >
              + 新增车牌号
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="驻点位置" prop="arrestPoint">
            <el-input
              v-model="form.arrestPoint"
              placeholder="请输入驻点地理位置"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">施工人员信息</el-divider>

      <el-table
        :data="form.constructorList"
        border
        style="width: 100%; margin-bottom: 20px"
      >
        <el-table-column label="人员类型" prop="constructPersonType">
          <template slot-scope="scope">
            <el-form-item
              :prop="'constructorList.' + scope.$index + '.constructPersonType'"
              :rules="{
                required: true,
                message: '请选择人员类型',
                trigger: 'change',
              }"
              style="margin-bottom: 0"
            >
              <el-select
                v-model="scope.row.constructPersonType"
                placeholder="请选择人员类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in personTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="人员姓名" prop="constructPersonnelName">
          <template slot-scope="scope">
            <el-form-item
              :prop="
                'constructorList.' + scope.$index + '.constructPersonnelName'
              "
              :rules="{
                required: true,
                message: '请输入人员姓名',
                trigger: 'blur',
              }"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="scope.row.constructPersonnelName"
                placeholder="请输入人员姓名"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="联系电话" prop="constructPersonnelPhone">
          <template slot-scope="scope">
            <el-form-item
              :prop="
                'constructorList.' + scope.$index + '.constructPersonnelPhone'
              "
              :rules="{
                required: true,
                message: '请输入联系电话',
                trigger: 'blur',
              }"
              style="margin-bottom: 0"
            >
              <el-input
                v-model="scope.row.constructPersonnelPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot="header">
            <span>操作</span>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              style="margin-left: 5px"
              @click="addConstructor"
            >
            </el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              v-if="form.constructorList.length > 1"
              type="text"
              icon="el-icon-delete"
              @click="removeConstructor(scope.$index)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { addEditConstructTeam } from "@/api/powerdistribution/team-manage";
import { personTypeOptions } from "../team.data";
export default {
  name: "TeamManageAddEdit",
  data() {
    return {
      personTypeOptions,
      visible: false,
      loading: false,
      isEdit: false,
      form: {
        countyOrgNm: "",
        teamNm: "",
        legalPerson: "",
        legalContactPhone: "",
        teamSerialNo: 1,
        teamLeader: "",
        teamLeaderPhone: "",
        construcCarNumber: [],
        arrestPoint: "",
        constructorList: [
          {
            constructPersonType: "",
            constructPersonnelName: "",
            constructPersonnelPhone: "",
          },
        ],
      },
      rules: {
        countyOrgNm: [
          { required: true, message: "请输入区县公司", trigger: "blur" },
        ],
        teamNm: [
          { required: true, message: "请输入队伍名称", trigger: "blur" },
        ],
        legalPerson: [
          { required: true, message: "请输入法人代表", trigger: "blur" },
        ],
        legalContactPhone: [
          { required: true, message: "请输入法人联系电话", trigger: "blur" },
        ],
        teamSerialNo: [
          { required: true, message: "请输入施工小组序号", trigger: "blur" },
        ],
        teamLeader: [
          { required: true, message: "请输入小组负责人", trigger: "blur" },
        ],
        teamLeaderPhone: [
          { required: true, message: "请输入负责人电话", trigger: "blur" },
        ],
        construcCarNumber: [
          {
            type: "array",
            required: true,
            message: "请至少输入一个作业车牌号",
            trigger: "change",
          },
        ],
        arrestPoint: [
          { required: true, message: "请输入驻点位置", trigger: "blur" },
        ],
      },
      inputVisible: false,
      inputValue: "",
    };
  },
  methods: {
    init(data) {
      this.visible = true;
      if (data) {
        this.isEdit = true;
        this.form = JSON.parse(
          JSON.stringify({
            ...data,
            constructorList:
              Array.isArray(data.constructorList) &&
              data.constructorList.length > 0
                ? data.constructorList
                : [
                    {
                      constructPersonType: "",
                      constructPersonnelName: "",
                      constructPersonnelPhone: "",
                    },
                  ],
          })
        );
      } else {
        this.isEdit = false;
        this.reset();
      }
    },
    reset() {
      this.$refs.form?.resetFields();
      if (!this.isEdit) {
        this.form = {
          countyOrgNm: "",
          teamNm: "",
          legalPerson: "",
          legalContactPhone: "",
          teamSerialNo: 1,
          teamLeader: "",
          teamLeaderPhone: "",
          construcCarNumber: [],
          arrestPoint: "",
          constructorList: [
            {
              constructPersonType: "",
              constructPersonnelName: "",
              constructPersonnelPhone: "",
            },
          ],
        };
      }
    },
    addConstructor() {
      this.form.constructorList.push({
        constructPersonType: "",
        constructPersonnelName: "",
        constructPersonnelPhone: "",
      });
    },
    removeConstructor(index) {
      this.form.constructorList.splice(index, 1);
    },
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const submitData = {
              ...this.form,
            };
            await addEditConstructTeam(submitData);
            this.$modal.msgSuccess(this.isEdit ? "修改成功" : "新增成功");
            this.$emit("success");
            this.visible = false;
          } catch (error) {
            console.error(error);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    cancel() {
      this.visible = false;
      this.reset();
    },
    handleClose(tag) {
      const index = this.form.construcCarNumber.indexOf(tag);
      if (index > -1) {
        this.form.construcCarNumber.splice(index, 1);
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        const carNumReg =
          /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{4,5}[A-Z0-9挂学警港澳]$/;
        if (!carNumReg.test(inputValue)) {
          this.$message.warning("请输入正确的车牌号格式");
          return;
        }
        if (this.form.construcCarNumber.includes(inputValue)) {
          this.$message.warning("该车牌号已存在");
          return;
        }
        this.form.construcCarNumber.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.constructor-item {
  position: relative;
  padding: 20px;
  padding-bottom: 0;
  border: 1px dashed #dcdfe6;
  margin-bottom: 10px;
  border-radius: 4px;

  .delete-btn {
    position: absolute;
    right: 10px;
    top: 10px;
  }
}

.text-center {
  text-align: center;
  margin: 20px 0;
}

::v-deep .el-input-number {
  width: 100%;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

// 标签容器样式
.el-form-item ::v-deep .el-form-item__content {
  //   border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 40px;
  padding: 5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  &:hover {
    border-color: #c0c4cc;
  }

  .el-tag {
    margin: 2px 5px;
  }
}

// 添加表格相关样式
::v-deep {
  .el-table {
    .el-form-item {
      margin-bottom: 0;

      .el-form-item__content {
        margin-left: 0 !important;
      }

      .el-form-item__error {
        position: absolute;
        top: 100%;
        z-index: 1;
      }
    }

    .el-table__cell {
      padding: 5px;
    }

    // 添加下拉框样式调整
    .el-select {
      width: 100%;

      .el-input__inner {
        // border: none;
        padding-left: 8px;
      }
    }

    // 添加表头按钮样式
    .el-table__header-wrapper {
      .el-button--mini {
        padding: 5px 8px;
      }
    }
  }
}
</style>
