<template>
  <el-dialog
    class="page-dialog"
    :visible.sync="modalIsShow"
    top="10px"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
    @open="visibleChange"
  >
    <div class="box-justify" slot="title">
      <h3>应用关联机构</h3>
      <div>
        <el-button
          size="mini"
          type="primary"
          :disabled="isSubmit"
          @click="submit"
          >确定</el-button
        >
        <el-button size="mini" type="danger" plain @click="cancel"
          >取消</el-button
        >
      </div>
    </div>

    <el-tabs v-model="tabType" type="card" @tab-click="tabChange">
      <el-tab-pane name="selected">
        <span slot="label">
          <span>已选机构</span>
          <span class="color-primary">({{ curSelectedOrgs.length }})</span>
        </span>

        <el-table :data="curSelectedOrgs">
          <!-- <el-table-column width="60" type="index" label="序号" align="center">
          </el-table-column> -->
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="名称"> </el-table-column>
          <el-table-column prop="code" label="编码"> </el-table-column>
          <el-table-column prop="typeName" label="一级分类" width="100">
          </el-table-column>
          <el-table-column prop="subTypesName" label="二级分类">
          </el-table-column>
          <el-table-column label="状态" width="100">
            <span
              slot-scope="scope"
              :class="{ 'color-primary': scope.row.selected }"
            >
              {{ scope.row.selected ? "已选择" : "未选择" }}
            </span>
          </el-table-column>
          <el-table-column label="操作" width="80" class-name="action-column">
            <div slot-scope="scope">
              <el-button
                class="btn-danger"
                type="text"
                @click="toDeleteSelected(scope.row)"
              >
                删除
              </el-button>
            </div>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="resource">
        <span slot="label">机构筛选</span>

        <div class="part-box-filter" style="padding: 0 0 5px">
          <el-form :model="filter" inline>
            <el-form-item label="一级分类">
              <el-select
                v-model="filter.type"
                placeholder="选择一级分类"
                clearable
                @change="typeChange"
              >
                <el-option
                  v-for="item in orgTypes"
                  :key="item.code"
                  :value="item.code"
                  :label="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="二级分类">
              <el-select
                v-model="filter.subType"
                placeholder="选择二级分类"
                clearable
              >
                <el-option
                  v-for="item in curSubTypes"
                  :key="item.code"
                  :value="item.code"
                  :label="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="编码" label-width="50">
              <el-input
                v-model="filter.code"
                placeholder="编码"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="模糊查询">
              <el-input
                v-model.trim="filter.nameStartWith"
                placeholder="名称前缀"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="toPage(1)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table :data="orgs">
          <!-- <el-table-column
            width="60"
            type="index"
            label="序号"
            align="center"
            :index="indexMethod"
          >
          </el-table-column> -->
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="名称"> </el-table-column>
          <el-table-column prop="code" label="编码"> </el-table-column>
          <el-table-column prop="typeName" label="一级分类" width="100">
          </el-table-column>
          <el-table-column prop="subTypesName" label="二级分类">
          </el-table-column>
          <el-table-column label="状态" width="100">
            <span
              slot-scope="scope"
              :class="{ 'color-primary': scope.row.selected }"
            >
              {{ scope.row.selected ? "已选择" : "未选择" }}
            </span>
          </el-table-column>
          <el-table-column label="操作" width="80" class-name="action-column">
            <div slot-scope="scope">
              <el-button
                v-if="scope.row.selected"
                class="btn-danger"
                type="text"
                @click="toDelete(scope.row)"
              >
                删除
              </el-button>
              <el-button
                v-else
                class="btn-primary"
                type="text"
                @click="toSelect(scope.row)"
              >
                添加
              </el-button>
            </div>
          </el-table-column>
        </el-table>

        <div class="part-page">
          <el-pagination
            background
            layout="total,prev, pager, next"
            :current-page="current"
            :total="total"
            :page-size="size"
            @current-change="toPage"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer"></div>
  </el-dialog>
</template>

<script>
import { orgQuery, appDeployOrgList, appDeployOrgUpdate } from "../api";

export default {
  name: "app-deploy-bind-org",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      filter: {
        type: "",
        subType: "",
        code: "",
        nameStartWith: "",
      },
      isSubmit: false,
      tabType: "selected",
      current: 1,
      size: 10,
      total: 10,
      orgTypes: this.$ls.get("orgTypes", []),
      orgTypeMap: this.$ls.get("orgTypeMap", {}),
      curSubTypes: [],
      orgs: [],
      curSelectedOrgs: [],
      curSelectedOrgIds: [],
    };
  },
  methods: {
    async initData() {
      await this.getSelectedOrgs();
      if (this.curSelectedOrgs && this.curSelectedOrgs.length) {
        this.tabType = "selected";
      } else {
        this.tabType = "resource";
        this.toPage(this.current);
      }
    },
    visibleChange() {
      this.initData();
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    typeChange() {
      const curType = this.orgTypes.find(
        (item) => item.code === this.filter.type
      );
      this.curSubTypes = curType ? curType.subTypes : [];
      this.filter.subType = null;
    },
    async getSelectedOrgs() {
      const res = await appDeployOrgList(this.instance.id);
      const resData = res || [];
      this.curSelectedOrgs = resData.map((item) => {
        item.typeName = this.orgTypeMap[item.type].name;
        item.selected = true;
        if (item.subTypes && item.subTypes.length) {
          item.subTypesName = item.subTypes
            .map((type) => this.orgTypeMap[item.type].subType[type])
            .join("，");
        }
        return item;
      });
      this.updateSelectedOrgIds();
    },
    indexMethod(index) {
      return index + (this.current - 1) * this.size + 1;
    },
    async getList() {
      const res = await orgQuery({
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      });
      this.orgs = res.records.map((item) => {
        item.typeName = this.orgTypeMap[item.type].name;
        item.selected = this.curSelectedOrgIds.includes(item.id);
        if (item.subTypes && item.subTypes.length) {
          item.subTypesName = item.subTypes
            .map((type) => this.orgTypeMap[item.type].subType[type])
            .join("，");
        }
        return item;
      });
      this.total = res.total;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    tabChange(val) {
      if (val.name === "resource") {
        if (this.orgs.length) {
          this.orgs.forEach((item) => {
            item.selected = this.curSelectedOrgIds.includes(item.id);
          });
        } else {
          this.toPage(this.current);
        }
      }
    },
    toSelect(row) {
      row.selected = true;
      this.curSelectedOrgs.push({ ...row });
      this.updateSelectedOrgIds();
    },
    toDelete(row) {
      row.selected = false;
      this.toDeleteSelected(row);
    },
    toDeleteSelected(row) {
      const pos = this.curSelectedOrgs.findIndex((item) => item.id === row.id);
      this.curSelectedOrgs.splice(pos, 1);

      this.updateSelectedOrgIds();
    },
    updateSelectedOrgIds() {
      this.curSelectedOrgIds = this.curSelectedOrgs.map((item) => item.id);
    },
    async submit() {
      if (!this.curSelectedOrgIds.length) {
        const result = await this.$confirm("确定不关联任何机构吗？", "警告", {
          type: "warning",
        }).catch(() => {});
        if (result !== "confirm") return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;
      const datas = {
        id: this.instance.id,
        orgId: this.curSelectedOrgIds.length ? this.curSelectedOrgIds : "",
      };
      const data = await appDeployOrgUpdate(datas).catch(() => {
        this.isSubmit = false;
      });

      if (!data) return;

      this.isSubmit = false;
      this.$message.success("关联成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
