<template>
  <el-dialog
    v-dialogDrag
    :title="departTitle"
    :visible="showdialog"
    @close="cancelForm"
    :close-on-click-modal="false"
  >
    <el-form
      class="form"
      :class="disabled ? 'disable-form' : ''"
      :disabled="disabled"
      label-width="120px"
      :model="datas"
      :rules="rules"
      ref="ruleForm"
    >
      <el-row>
        <!-- 详情 -->
        <el-col :span="24" v-if="disabled">
          <div class="flexc">
            <span class="label">组织名称：</span>
            <span>{{ datas.selectedOrganizationName || "-" }}</span>
          </div>
          <div class="flexc">
            <span class="label">组织说明：</span>
            <span>{{ datas.selectedOrganizationNote || "-" }}</span>
          </div>
          <div class="flexc">
            <span class="label">组织编码：</span>
            <span>{{ datas.code || "-" }}</span>
          </div>
          <div class="flexc">
            <span class="label">组织状态：</span>
            <span class="green" :class="datas.status">{{
              statusMap[datas.status] || "-"
            }}</span>
          </div>
          <div class="flexc">
            <span class="label">组织类型：</span>
            <span>{{
              datas.organizationType?.organizationTypeName || "-"
            }}</span>
          </div>
          <div class="flexc">
            <span class="label">统一信用代码：</span>
            <span v-if="datas.statistics?.unifySocialCreditCode"
              >{{ datas.statistics.unifySocialCreditCode }}
              <i
                style="color: #0076f6"
                slot="suffix"
                @click="changeType(datas.statistics, 'unifySocialCreditCode')"
                class="el-icon-view"
              ></i
            ></span>
            <span v-else>-</span>
          </div>
          <div class="flexc">
            <span class="label" style="flex-shrink: 0;">组织管理员：</span>
            <div style="display: flex; flex-wrap: wrap" v-if="adminList.length">
              <div
                style="margin-right: 12px;margin-top: 6px;"
                v-for="ix in adminList"
                :key="ix.id"
              >
                <span
                  >{{ ix.name }} （{{ ix.telephone }}）

                  <i
                    style="color: #0076f6"
                    slot="suffix"
                    @click="changeType(ix, 'telephone')"
                    class="el-icon-view"
                  ></i
                ></span>
              </div>
            </div>
            <span v-else>-</span>
          </div>

          <div class="flexc">
            <span class="label">组织联系人：</span>
            <div style="display: flex; flex-wrap: wrap">
              <div>
                <span v-if="datas.contactName"
                  >{{ datas.contactName }} （{{ datas.contactTelephone }}）
                  <i
                    style="color: #0076f6"
                    slot="suffix"
                    @click="changeType(datas, 'contactTelephone')"
                    class="el-icon-view"
                  ></i
                ></span>
                <span v-else>-</span>
              </div>
            </div>
          </div>

          <div class="flexc">
            <span class="label">员工数量：</span>
            <span>{{ datas.statistics?.countOfMembers || "-" }}</span>
          </div>
        </el-col>
        <!-- 编辑 -->

        <el-col :span="24" v-else>
          <el-form-item label="组织名称：" prop="selectedOrganizationName">
            <el-input
              disabled
              v-model="datas.selectedOrganizationName"
              :placeholder="placeholder"
            ></el-input>
          </el-form-item>
          <el-form-item label="组织说明：" prop="selectedOrganizationNote">
            <div style="display: flex">
              <el-input
                v-model="datas.selectedOrganizationNote"
                :placeholder="placeholder"
              ></el-input>
              <span style="margin-left: 16px">
                通过说明快速标注组织（如简称、别称等），增加辨识度。</span
              >
            </div>
          </el-form-item>

          <el-form-item label="组织类型：" prop="organizationTypeId">
            <el-select v-model="datas.organizationTypeId" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上级组织：" prop="parentId">
            <el-cascader
				ref="cascaderRef"
				:show-all-levels="false"
				style="width: 100%"
				:props="{ checkStrictly: true }"
				:options="propTableData || []"
				v-model="datas.parentId"
				placeholder="请选择"
				@change="changeParentId"
            />
          </el-form-item>
          <el-form-item label="组织编码：" prop="code">
            <div style="display: flex">
              <el-input
                v-model="datas.code"
                :placeholder="placeholder"
              ></el-input>
              <span style="margin-left: 16px"> 如有组织编码可记录归档。</span>
            </div>
          </el-form-item>
          <el-form-item label="联系人：" prop="contactName">
            <div style="display: flex">
              <el-input
                v-model="datas.contactName"
                :placeholder="placeholder"
              ></el-input>
              <span style="margin-left: 16px">
                组织的系统联系人，信息会展示在集团架构图上。</span
              >
            </div>
          </el-form-item>
          <el-form-item label="电话：" prop="contactTelephone">
            <el-input
              v-model="datas.contactTelephone"
              :placeholder="placeholder"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="!disabled" @click="submitForm()"
        >确 定</el-button
      >
      <el-button @click="cancelForm()">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  getAdminList,
  getfindByOrganizationId,
  updateOrganizationInfo,
} from "@/api/staffApi.js";
export default {
  props: ["showdialog", "dataInfo", "disabled", "tableData"],

  components: {},
  data() {
    return {
      statusMap: {
        Refuse: "已拒绝",
        TargetRefuse: "对方已拒绝",
        TargetVerify: "待对方确认",
        Verify: "待确认",
        Related: "已关联",
      },
      title: "",
      departTitle: "组织详情",
      rules: {
        selectedOrganizationNote: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
        parentId: [{ required: true, message: "请选择", trigger: "blur" }],
        organizationTypeId: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        contactName: [{ required: true, message: "请输入", trigger: "blur" }],
        contactTelephone: [
          { required: true, message: "请输入", trigger: "blur" },
        ],
      },
      options: [],
      value: "",
      datas: {},
      adminList: [],
      propTableData: [],
    };
  },

  watch: {
    showdialog: {
      handler() {
        if (!this.showdialog || !this.dataInfo.selectedOrganizationId) return;
        this.datas = {
          ...this.dataInfo,
          organizationTypeId:
            this.dataInfo?.organizationType?.organizationTypeId,
        };
		console.log(this.datas)
        if (this.datas.statistics) {
          this.transformType(this.datas.statistics, "unifySocialCreditCode");
          this.transformType(this.datas, "contactTelephone");
        }
        if (this.tableData?.length&&!this.disabled) {
          this.propTableData=JSON.parse(JSON.stringify(this.tableData));
          this.mapData(this.propTableData,this.datas.selectedOrganizationId);
        }
        this.getAdminList();
        this.getfindByOrganizationId();
      },
      deep: true,
    },
  },

  computed: {
    placeholder() {
      return this.disabled ? "" : "请填写";
    },
  },

  methods: {
    mapData(data,disId,pd=false) {//只为上级组织做数据
      data.forEach((ex) => {
        ex.value = ex.selectedOrganizationId;
        ex.label = ex.selectedOrganizationName;
        if(pd||disId===ex.value) {
          ex.disabled=true;

        }
        if (ex.children?.length) {
          this.mapData(ex.children,disId,pd||disId===ex.value);
        } else {
          delete ex.children;
        }
      });
    },
    getfindByOrganizationId() {
      getfindByOrganizationId(this.datas.selectedOrganizationId).then((response) => {
        if (response.data) {
          this.options = response.data;
        }
      });
    },

    getAdminList() {
      if (!this.datas.selectedOrganizationId) return;
      getAdminList(this.datas.selectedOrganizationId).then((res) => {
        if (res.data) {
          res.data?.forEach((element) => {
            this.transformType(element, "telephone");
          });
          this.adminList = res.data;
        }
      });
    },
    changeType(data, v) {
      let t = data[v];
      this.$set(data, v, data[`old_${v}`]);
      this.$set(data, `old_${v}`, t);
    },
	changeParentId(value) {
		let row = this.$refs.cascaderRef.getCheckedNodes()
		this.datas.parentname = row[0].data.label
	},	
    transformType(data, v) {
      let t = data[v];
      // 确保输入的字符串至少有7个字符
      if ((t && t.length < 7) || !t) {
        return;
      }
      this.$set(
        data,
        v,
        t.substring(0, 3) + "*".repeat(t.length - 6) + t.substring(t.length - 3)
      );
      this.$set(data, `old_${v}`, t);

      // 例子
    },
    cancelForm() {
      //取消关闭
      this.$emit("update:showdialog", false);
    },

    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const {
            code,
            contactName,
            contactTelephone,
            id,
            organizationTypeId,
            parentId,
			parentname,
          } = this.datas;
          let params = {
            code,
            contactName,
            contactTelephone,
            id,
            organizationNote: this.datas.selectedOrganizationNote,
            organizationTypeId,
            parentId: parentId[parentId.length - 1],
			parentname,
          };
          console.log(params);
          updateOrganizationInfo(params).then((res) => {
            if (res.status == 200) {
              this.$message.success("修改成功");
              this.$emit("update:showdialog", false);
              this.$emit("getData");
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.Refuse,
.TargetRefuse {
  color: red;
}
.TargetVerify,
.Verify {
  color: goldenrod;
}
.Related {
  color: green;
}

.flexc {
  display: flex;
  align-items: center;
}
.label {
  width: 120px;
  text-align: right;
  display: inline-block;
  margin: 12px;
}
.green {
  color: #70b603;
}
.disable-form {
  /deep/ {
    .el-input__inner {
      border: none !important;
    }
  }
}

.form {
  padding: 18px 32px;
  max-height: 60vh;
  overflow: auto;
  /deep/ .el-input {
    margin-left: 12px;
  }
  /deep/ .el-form-item__content {
    .el-input {
      width: 40%;
    }
    .el-select {
      width: 100%;
    }
  }
}
</style>
