<template>
  <el-dialog
    :title="!type == 'add' ? '新增成员' : '编辑成员'"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="visible"
    :modal="false"
    lock-scroll
    class="JNPF-dialog JNPF-dialog_center"
    fullscreen
  >
    <el-form
      ref="personForm"
      :model="personForm"
      :roles="dataRule"
      label-width="80px"
      v-loading="formLoading"
      class="menuForm"
    >
      <el-form-item label="成员名称" prop="name" v-if="type == 'add'">
        <el-select
          v-model="personForm.user"
          filterable
          remote
          value-key="id"
          reserve-keyword
          placeholder="请输入成员姓名进行搜索"
          :remote-method="remoteMethod"
          :loading="selectLoding"
        >
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.realName + '（' + item.account + '）'"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="成员名称" prop="name" v-if="type == 'edit'">
        <span>{{ personForm.userLabel }}</span>
      </el-form-item>

      <el-form-item label="是否组长" prop="bodyText">
        <el-switch
          v-model="personForm.leader"
          active-color="#1890ff"
          inactive-color="#c0c4cc"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="角色" prop="bodyText">
        <el-select v-model="personForm.teamRole" placeholder="请选择角色">
          <el-option
            v-for="item in roles"
            :key="item.enCode"
            :label="item.fullName"
            :value="item.enCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责厅局" prop="bodyText">
        <div class="" style="margin-bottom: 10px;">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="orgDialoghandleShow()"
            >新增厅局</el-button
          >
        </div>
        <JNPF-table
          v-loading="formLoading"
          :data="personForm.orgInfo"
          :key="tamptime"
        >
          <el-table-column prop="organizeLabel" label="名字" />
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <tableOpts @del="deleteOrg(scope.$index)" :hasEdit="false">
              </tableOpts>
            </template>
          </el-table-column>
        </JNPF-table>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{
        $t("common.cancelButton")
      }}</el-button>
      <el-button
        type="primary"
        :loading="btnLoading"
        @click="personFormSubmit()"
      >
        {{ $t("common.confirmButton") }}</el-button
      >
    </span>
    <el-dialog
      title="选择厅局"
      :visible.sync="orgDialogVisible"
      width="30%"
      append-to-body
      class="JNPF-dialog JNPF-dialog_center"
    >
      <el-cascader
        :options="orgOptions"
        v-model="orgValue"
        :props="{ checkStrictly: true, label: 'fullName', value: 'id' }"
        clearable
        filterable
        @change="handleChange"
      ></el-cascader>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orgDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="orgDialoghandleClose"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { findOrganizeList } from "@/api/governmentCloud/bureauSystemManage/bureauSystemManage";
import { getDepartmentSelectorByAuth } from "@/api/permission/department";

import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import { getUserList } from "@/api/permission/user";

export default {
  data() {
    return {
      visible: false,
      personForm: {
        leader: false,
        teamRole: "",
        userLabel: "",
        userKey: "",
        orgInfo: [],
        user: {}
      },
      selectLoding: false,
      userList: [],
      dataRule: {
        userLabel: [
          { required: true, message: "成员名称不能为空", trigger: "blur" }
        ]
      },
      formLoading: false,
      btnLoading: false,
      roles: [],
      type: null,
      tamptime: null,
      orgDialogVisible: false,
      orgOptions: [],
      orgValue: null,
      selectedObject: null
    };
  },
  async mounted() {
    this.formLoading = true;
    this.roles = await this.getRoles();
    this.orgOptions = await this.getOrgOptions();
    this.formLoading = false;
  },
  methods: {
    handleChange(value) {
      console.log(value);
      console.log(value[value.length - 1]);
      // 当选中项变化时，可以在这里处理选中对象
      // 例如根据value找到对应的对象
      this.selectedObject = this.findObjectByValue(
        this.orgOptions,
        value[value.length - 1]
      );
    },
    findObjectByValue(options, value) {
      // 递归查找整个树，并返回匹配的对象
      for (let option of options) {
        if (option.id === value) {
          return option;
        }
        if (option.children && option.children.length > 0) {
          const found = this.findObjectByValue(option.children, value);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },
    remoteMethod(query) {
      console.log(query);
      if (query !== "") {
        this.selectLoding = true;
        let listQuery = {
          keyword: query
        };
        getUserList(listQuery)
          .then(res => {
            this.userList = res.data.list.filter(item => {
              return (
                item.realName.toLowerCase().indexOf(query.toLowerCase()) > -1
              );
            });
            this.selectLoding = false;
          })
          .catch(() => {
            this.listLoading = false;
          });
      } else {
        this.options = [];
      }
    },
    init(type, row) {
      this.type = type;
      this.tamptime = new Date().valueOf();
      if (this.type == "add") {
        for (const key in this.personForm) {
          this.personForm[key] = "";
          this.personForm.leader = false;
        }
        this.personForm.orgInfo = [];
      } else {
        console.log(row);
        let obj = JSON.parse(JSON.stringify(row));
        console.log(obj);
        this.personForm = obj;
        this.personForm.user = {
          realName: obj.userLabel,
          id: obj.userKey
        };
      }
      this.visible = true;
      this.$nextTick(() => {});
    },
    personFormSubmit() {
      this.$refs["personForm"].validate(valid => {
        if (valid) {
          let row = JSON.parse(JSON.stringify(this.personForm));
          row.userLabel = row.user.realName;
          row.userKey = row.user.id;
          delete row.user;
          if (this.type == "add") {
            this.$emit("addPersonData", row, "add");
          } else {
            this.$emit("addPersonData", row, "edit");
          }
          this.visible = false;
        }
      });
    },
    getRoles() {
      return new Promise((resolve, reject) => {
        getDictionaryDataSelector("teamRole").then(res => {
          resolve(res.data.list);
        });
      });
    },
    getOrgOptions() {
      return new Promise((resolve, reject) => {
        getDepartmentSelectorByAuth().then(res => {
          resolve(res.data.list);
        });
        // findOrganizeList().then(res => {
        //   resolve(res.data);
        // });
      });
    },
    findRoleLabel(value) {
      let label = "";
      this.roles.map(item => {
        if (item.enCode == value) {
          label = item.fullName;
        }
        return label;
      });
    },
    // 新增成员
    addPerson() {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.Form.init("1");
      });
    },
    orgSelectChange(e) {
      console.log(e);
    },
    //开启厅局选择
    orgDialoghandleShow() {
      this.orgValue = null;
      this.orgDialogVisible = true;
    },
    // 关闭厅局选择
    orgDialoghandleClose() {
      if (this.selectedObject) {
        let obj = {
          organizeKey: this.selectedObject.id,
          organizeLabel: this.selectedObject.fullName
        };
        if (!this.personForm.orgInfo) {
          this.personForm.orgInfo = [];
        }

        let flag = true;

        this.personForm.orgInfo.map(org => {
          if (org.organizeKey == obj.organizeKey) {
            flag = false;
          }
        });

        if (flag) {
          this.personForm.orgInfo.push(obj);
          this.tamptime = new Date().valueOf();
          this.orgDialogVisible = false;
        } else {
          this.$message.warning("请不要选择重复厅局");
          this.orgValue = null;
        }
      } else {
        this.$message.warning("请选择厅局");
      }
    },
    // 删除厅局
    deleteOrg(index) {
      this.personForm.orgInfo.splice(index, 1);
    }
  }
};
</script>
