<template>
  <div class="app-container">
    <!-- 主对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="65%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="150px"
      >
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="12">
            <el-form-item label="网站名称：" prop="websiteName">
              <el-select
                v-model="formData.websiteName"
                placeholder="请选择网站名称"
                style="width: 100%"
                @change="handleWebsiteNameChange"
              >
                <el-option
                  v-for="dict in availableWebsiteOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="网站网址：" prop="websiteUrl">
              <el-input
                v-model="formData.websiteUrl"
                placeholder="请输入网站网址"
                readonly
              />
            </el-form-item>
            <el-form-item label="网站上线日期：" prop="launchDate">
              <el-date-picker
                clearable
                v-model="formData.launchDate"
                type="date"
                value-format="timestamp"
                placeholder="选择网站上线日期"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="网站负责人姓名：" prop="ownerName">
              <el-input
                v-model="formData.ownerName"
                placeholder="请输入网站负责人姓名"
              />
            </el-form-item>
            <el-form-item label="负责人电话：" prop="ownerPhone">
              <el-input
                v-model="formData.ownerPhone"
                placeholder="请输入负责人电话"
              />
            </el-form-item>
            <el-form-item label="网站所属部门：" prop="websiteDeptName">
              <el-row :gutter="10">
                <el-col :span="17">
                  <el-select
                    v-model="formData.websiteDeptName"
                    placeholder="请选择网站所属部门"
                    style="width: 100%"
                    @change="handleDeptChange"
                  >
                    <el-option
                      v-for="item in userList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
                <el-col :span="6">
                  <el-button
                    type="primary"
                    @click="showDeptManager"
                    :disabled="!formData.websiteDeptName"
                    style="width: 100%;padding:10px 1px;font-size:10px"
                  >
                    查看负责人
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="技术运维单位名称：" prop="techOrgName">
              <el-select
                v-model="formData.techOrgName"
                placeholder="请选择技术运维单位名称"
                style="width: 100%"
                :disabled="!hasSameDepartment()"
              >
                <el-option
                  v-for="item in suplierList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="主办单位：" prop="zborganizer">
              <el-input
                v-model="formData.zborganizer"
                placeholder="请输入主办单位"
              />
            </el-form-item>
            <el-form-item label="承办单位：" prop="cborganizer">
              <el-input
                v-model="formData.cborganizer"
                placeholder="请输入承办单位"
              />
            </el-form-item>
          </el-col>

          <!-- 第二列 -->
          <el-col :span="12">
            <el-form-item label="ICP备案号：" prop="icpRecordNo">
              <el-input
                v-model="formData.icpRecordNo"
                placeholder="请输入ICP备案号"
              />
            </el-form-item>
            <el-form-item label="公安备案号：" prop="policeRecordNo">
              <el-input
                v-model="formData.policeRecordNo"
                placeholder="请输入公安备案号"
              />
            </el-form-item>
            <el-form-item label="政府网站标识码：" prop="govSiteCode">
              <el-input
                v-model="formData.govSiteCode"
                placeholder="请输入政府网站标识码"
              />
            </el-form-item>
            <el-form-item label="办公地址：" prop="officeAddress">
              <el-input
                v-model="formData.officeAddress"
                placeholder="请输入办公地址"
              />
            </el-form-item>
            <el-form-item label="网站联系电话：" prop="contactPhone">
              <el-input
                v-model="formData.contactPhone"
                placeholder="请输入网站联系电话"
              />
            </el-form-item>
            <el-form-item label="IPV4地址：" prop="ipv4Address">
              <el-input
                v-model="formData.ipv4Address"
                placeholder="请输入IPV4地址"
              />
            </el-form-item>
            <el-form-item label="IPV6地址：" prop="ipv6Address">
              <el-input
                v-model="formData.ipv6Address"
                placeholder="请输入IPV6地址"
              />
            </el-form-item>
            <el-form-item label="HTTP映射端口：" prop="httpPort">
              <el-input
                v-model="formData.httpPort"
                placeholder="请输入HTTP映射端口"
              />
            </el-form-item>
            <el-form-item label="HTTPS映射端口：" prop="httpsPort">
              <el-input
                v-model="formData.httpsPort"
                placeholder="请输入HTTPS映射端口"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading"
        >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 部门负责人信息对话框 -->
    <el-dialog
      title="部门负责人信息"
      :visible.sync="managerDialogVisible"
      width="30%"
      append-to-body
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="部门名称">{{ managerInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="负责人姓名">{{ managerInfo.leaderName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ managerInfo.phone || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="managerDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { DICT_TYPE } from '@/utils/dict'
import * as TechOrgApi from "@/api/server/techorg";
import * as WorkorderTypeApi from "@/api/server/WorkorderType";
import * as WorkorderInfosApi from '@/api/server/WorkorderInfos';
import { getDept } from "@/api/system/dept";
import {getUser} from "@/api/system/user";

export default {
  name: "TechOrgForm",
  components: {},
  data() {
    return {
// 存储系统中已存在的网站名称
      existingWebsiteNames: new Set(),
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 部门负责人对话框相关
      managerDialogVisible: false,
      managerInfo: {
        name: '',
        leaderName: '',
        phone: ''
      },
      currentDeptName: '',
      // 表单参数
      formData: {
        id: undefined, // 确保有id字段用于区分新增/编辑
        websiteDept: undefined,
        websiteDeptName: undefined,
        techOrgId: undefined,
        techOrgName: undefined,
        websiteName: undefined,
        websiteUrl: undefined,
        launchDate: undefined,
        ownerName: undefined,
        ownerPhone: undefined,
        zborganizer: undefined,
        cborganizer: undefined,
        icpRecordNo: undefined,
        policeRecordNo: undefined,
        govSiteCode: undefined,
        officeAddress: undefined,
        contactPhone: undefined,
        ipv4Address: undefined,
        ipv6Address: undefined,
        httpPort: undefined,
        httpsPort: undefined,
      },
      // 表单校验
      formRules: {
/*        websiteName: [
          { required: true, message: "网站名称不能为空", trigger: "blur" },
        ],*/
        websiteUrl: [
          { required: true, message: "网站网址不能为空", trigger: "blur" },
        ],
        launchDate: [
          { required: true, message: "网站上线日期不能为空", trigger: "blur" },
        ],
        ownerName: [
          {
            required: true,
            message: "网站负责人姓名不能为空",
            trigger: "blur",
          },
        ],
        techOrgName: [
          {
            required: true,
            message: "技术运维单位名称不能为空",
            trigger: "blur",
          },
        ],
        websiteName: [
          { required: true, message: "网站名称不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // Check if value is an object (from select) or string
              const websiteName = typeof value === 'object' ? value.label : value;
              if (this.existingWebsiteNames.has(websiteName) && !this.formData.id) {
                callback(new Error("该网站名称已被使用"));
              } else {
                callback();
              }
            },
            trigger: "change" // Changed from 'blur' to 'change' for better UX with select
          }
        ],
        websiteDeptName: [
          { required: true, message: "网站所属部门不能为空", trigger: "blur" },
        ],
      },
      suplierList: [],
      userList: [],
    };
  },
  computed: {
    // 可选的网站名称选项（过滤掉已存在的）
    availableWebsiteOptions() {
      const allOptions = this.getDictDatas(DICT_TYPE.TRS_TECH_ORG) || [];
      return allOptions.filter(option =>
        !this.existingWebsiteNames.has(option.label) ||
        (this.formData.id && this.formData.websiteName === option.label)
      );
    }
  },
  methods: {
    /** 检查当前用户是否与数据创建人同部门 */
    hasSameDepartment() {
      // 获取当前用户角色信息
      const userInfo = this.$store.state.user;
      const roles = userInfo.roles || []; // 假设角色信息存储在roles数组中
      // 如果用户有超管角色（id是1），则返回true
      if (roles.includes("super_admin")) {
        return true;
      }
    },

    /** 加载已存在的网站名称 */
    async loadExistingWebsiteNames() {
      try {
        const res = await TechOrgApi.getTechOrgList();
        const names = res.data.map(item => item.websiteName);
        this.existingWebsiteNames = new Set(names);
      } catch (error) {
        console.error("加载已有网站名称失败:", error);
        this.existingWebsiteNames = new Set();
      }
    },

    /** 获取可选的网站名称列表 */
    getAvailableWebsiteOptions() {
      const allOptions = this.getDictDatas(DICT_TYPE.TRS_TECH_ORG);
      return allOptions.filter(option =>
        !this.selectedWebsiteNames.has(option.label)
      );
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();

      // 加载已存在的网站名称
      await this.loadExistingWebsiteNames();

      if (id) {
        this.formLoading = true;
        try {
          const res = await TechOrgApi.getTechOrg(id);
          this.formData = res.data;
          this.dialogTitle = "修改网站信息";

          // 编辑时设置选择器
          if (this.formData.websiteUrl) {
            const dict = this.getDictDatas(DICT_TYPE.TRS_TECH_ORG).find(
              item => item.value === this.formData.websiteUrl
            );
            if (dict) {
              this.$nextTick(() => {
                this.formData.websiteName = dict.label;
              });
            }
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增网站信息";
      }
    },

    /** 处理网站名称变化 */
    handleWebsiteNameChange(selectedDict) {
      if (selectedDict) {
        this.formData.websiteName = selectedDict.label; // 存储名称
        this.formData.websiteUrl = selectedDict.value; // 存储网址
      } else {
        this.formData.websiteName = undefined;
        this.formData.websiteUrl = undefined;
      }
    },

    /** 部门变更处理 */
    handleDeptChange(deptId) {
      this.formData.websiteDept = deptId;
    },

    /** 显示部门负责人信息 */
    async showDeptManager() {
      if (!this.formData.websiteDeptName) return;

      try {
        // 获取当前部门名称
        const dept = this.userList.find(item => item.id === this.formData.websiteDeptName);
        this.currentDeptName = dept ? dept.name : '';

        let deptId = this.formData.websiteDept;
        if (typeof this.formData.websiteDeptName === 'number') {
          deptId = this.formData.websiteDeptName;
        }

        // 使用await替代.then()保持代码风格一致
        const deptRes = await getDept(deptId);

        if (!deptRes.data || !deptRes.data.leaderUserId) {
          this.managerInfo = {
            name: deptRes.data?.name || '无',
            leaderName: '无',
            phone: '无'
          };
          this.managerDialogVisible = true;
          return;
        }

        // 获取负责人信息
        let userName = '无';
        try {
          const userRes = await getUser(deptRes.data.leaderUserId);
          userName = userRes.data.nickname || '无';
        } catch (error) {
          console.error("获取用户信息失败:", error);
          // 不显示错误，保持用户体验
        }

        this.managerInfo = {
          name: deptRes.data.name || '无',
          leaderName: userName,
          phone: deptRes.data.phone || '无'
        };

        this.managerDialogVisible = true;
      } catch (error) {
        console.error("获取部门负责人信息失败:", error);
        this.$message.error("获取部门负责人信息失败");
        this.managerInfo = {
          name: '无',
          leaderName: '无',
          phone: '无'
        };
        this.managerDialogVisible = true;
      }
    },

    /** 提交按钮 */
    async submitForm() {
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        if (data.id) {
          await TechOrgApi.updateTechOrg(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          await TechOrgApi.createTechOrg(data);
          this.$modal.msgSuccess("新增成功");
          // 新增成功后刷新已存在网站名称列表
          await this.loadExistingWebsiteNames();
        }
        this.dialogVisible = false;
        this.$emit("success");
      } finally {
        this.formLoading = false;
      }
    },

    /** 表单重置 */
    reset() {
      this.formData = {
        websiteName: undefined,
        websiteUrl: undefined,
        launchDate: undefined,
        ownerName: undefined,
        ownerPhone: undefined,
        techOrgName: undefined,
      };
      this.resetForm("formRef");
    },

    // 查询运维商
    async getSuplierList() {
      const res = await WorkorderTypeApi.suplierList();
      this.suplierList = res.data;
    },

    // 获取部门列表
    async getUserList() {
      const res = await WorkorderInfosApi.getUserList();
      this.userList = res.data;
    },
  },
  created() {
    this.getSuplierList();
    this.getUserList();
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: -20px;
}
.el-col {
  padding-right: 10px;
}
.el-form-item__label {
  white-space: nowrap;
}
/* 部门选择器与按钮的布局调整 */
.website-dept-container {
  display: flex;
  align-items: center;
}
.website-dept-select {
  flex: 1;
  margin-right: 10px;
}
</style>
