<template>
  <el-row>
    <el-col :span="12">
      <basic-container>
        <avue-crud :option="optionParent" :table-loading="loading" :data="dataParent" :page="pageParent" :permission="permissionList"
                   :before-open="beforeOpen" v-model="formParent" ref="crud" @row-click="handleRowClick" @row-update="rowUpdate"
                   @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
                   @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
                   @on-load="onLoadParent">
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.alarmgroup_delete"
                       @click="handleDelete">删 除
            </el-button>
          </template>
          <template slot="residentialId" slot-scope="scope">
            <div>{{scope.row.residentialName}}</div>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>

    <el-col :span="12">
      <basic-container>
        <avue-crud :option="optionChild" :table-loading="loadingChild" :data="dataChild" :page="pageChild" :permission="permissionListChild"
                   :before-open="beforeOpenChild" v-model="formChild" ref="crudChild" @row-update="rowUpdateChild" @row-save="rowSaveChild"
                   @row-del="rowDelChild" @search-change="searchChangeChild" @search-reset="searchResetChild" @selection-change="selectionChangeChild"
                   @current-change="currentChangeChild" @size-change="sizeChangeChild" @refresh-change="refreshChangeChild"
                   @on-load="onLoadChild">
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.alarmgroupuser_delete"
                       @click="handleDeleteChild">删 除
            </el-button>
          </template>

        </avue-crud>
      </basic-container>
    </el-col>

  </el-row>

</template>

<script>
  import {
    getList,
    getDetail,
    add,
    update,
    remove
  } from "@/api/device/iotalarmgroup";
  import {
    getList as getUserList,
    getDetail as getUserDetail,
    add as addUser,
    updata as updateUser,
    remove as removeUser
  } from "@/api/device/iotalarmgroupuser";
  import {
    mapGetters
  } from "vuex";

  var DIC = {
    yes_no: [{
      label: '否',
      value: 0
    }, {
      label: '是',
      value: 1
    }]
  }

  export default {
    data() {
      return {
        formParent: {},
        query: {},
        loading: true,
        pageParent: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        optionParent: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 8,
          border: true,
          index: true,
          viewBtn: true,
          dialogWidth: 600,
          selection: true,
          dialogClickModal: false,
          menuPosition: "center",
          menuWidth:340,
          column: [{
            label: "组名",
            prop: "name",
            row: true,
            span: 20,
            rules: [{
              required: true,
              message: "请输入组名",
              trigger: "blur"
            }]

          },
            {
              label: "归属",
              prop: "residentialId",
              span: 20,
              row: true,
              type: "select",
              searchSpan: 12,
              remote: true,
              //回显的时候有问题，如果所选不在前十条内，下拉框只会显示id
              dicUrl: "/api/cyzh-community/residential/list?size=10000&name={{key}}",
              props: {
                label: "name",
                value: "id"
              },
              searchFilterable: true,
              search: true,
              slot: true,
              rules: [{
                required: true,
                message: "请输入",
                trigger: "blur"
              }]
            },
            {
              label: "设备类型",
              prop: "tag",
              type: "select",
              row: true,
              span: 20,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=iot_device_type",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              dataType: "number",
              rules: [{
                required: true,
                message: "请输入标识",
                trigger: "blur"
              }]
            },
          ]
        },
        dataParent: [],
        //-----------------------------------------------------------------------------------------
        formChild: {},
        loadingChild: true,
        pageChild: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        optionChild: {
          height: 'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          menuPosition: "center",
          dialogWidth: 600,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          menuWidth:340,
          column: [{
            label: "责任人",
            prop: "person",
            row: true,
            span: 20,
            labelWidth: 120,
            rules: [{
              required: true,
              message: "请输入责任人",
              trigger: "blur"
            }]
          },
            {
              label: "责任人电话",
              prop: "phone",
              row: true,
              labelWidth: 120,
              span: 20,
              rules: [{
                required: true,
                message: "请输入责任人电话",
                trigger: "blur"
              }]
            },
            {
              label: "是否为处理人",
              prop: "isHandler",
              type: "switch",
              row: true,
              span: 20,
              labelWidth: 120,
              // dicData: DIC.yes_no,
              // mock: {
              //   type: 'dic'
              // },
              dicData:[
                {
                  label:'是',
                  value:true
                },
                {
                  label:'否',
                  value: false
                }
              ],
              displayAs: 'switch',
              rules: [{
                required: false,
                message: "请输入是否为处理人",
                trigger: "blur"
              }]
            },
          ]
        },
        dataChild: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.iotalarmgroup_add, false),
          viewBtn: this.vaildData(this.permission.iotalarmgroup_view, false),
          delBtn: this.vaildData(this.permission.iotalarmgroup_delete, false),
          editBtn: this.vaildData(this.permission.iotalarmgroup_edit, false)
        };
      },
      permissionListChild() {
        return {
          addBtn: this.vaildData(this.permission.iotalarmgroupuser_add, false),
          viewBtn: this.vaildData(this.permission.iotalarmgroupuser_view, false),
          delBtn: this.vaildData(this.permission.iotalarmgroupuser_delete, false),
          editBtn: this.vaildData(this.permission.iotalarmgroupuser_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      let tenantType = localStorage.getItem("tenantType");
      const residentialIdColumn = this.findObject(this.optionParent.column, "residentialId");
      if (tenantType == 1) { //园区
        residentialIdColumn.label = "所属区域"
      } else { //社区
        residentialIdColumn.label = "所属小区"
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoadParent(this.pageParent);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoadParent(this.pageParent);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.formParent.id).then(res => {
            this.formParent = res.data.data;
          });
        }
        done();
      },
      handleRowClick(row) {
        this.query = {};
        this.parentId = row.id;
        debugger
        this.dictValue = row.dictValue;
        this.$refs.crudChild.value.code = row.code;
        this.$refs.crudChild.value.parentId = row.id;
        // this.$refs.crudChild.option.column.filter(item => {
        //   if (item.prop === "code") {
        //     item.value = row.code;
        //   }
        //   if (item.prop === "parentId") {
        //     item.value = row.id;
        //   }
        // });
        this.onLoadChild(this.pageChild);
      },
      searchReset() {
        this.query = {};
        this.onLoadParent(this.pageParent);
      },
      searchChange(params, done) {
        this.query = params;
        this.pageParent.currentPage = 1;
        this.onLoadParent(this.pageParent, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage) {
        this.pageParent.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.pageParent.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoadParent(this.pageParent, this.query);
      },
      onLoadParent(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.pageParent.total = data.total;
          this.dataParent = data.records;
          if (this.dataParent.length > 0) {
            this.parentId = this.dataParent[0].id;
            this.onLoadChild(this.pageChild);
          }
          this.loading = false;
          this.selectionClear();
        });
      },
      rowSaveChild(row, done, loading) {
        row.groupId = this.parentId;
        addUser(row).then(() => {
          this.onLoadChild(this.pageChild);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdateChild(row, index, done, loading) {
        // row.groupId = this.parentId;
        updateUser(row).then(() => {
          this.onLoadChild(this.pageChild);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDelChild(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeUser(row.id);
          })
          .then(() => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDeleteChild() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpenChild(done, type) {
        if (["edit", "view"].includes(type)) {
          getUserDetail(this.formChild.id).then(res => {
            this.formChild = res.data.data;
          });
        }
        done();
      },
      searchResetChild() {
        this.query = {};
        this.onLoadChild(this.pageChild);
      },
      searchChangeChild(params, done) {
        this.query = params;
        this.pageChild.currentPage = 1;
        this.onLoadChild(this.pageChild, params);
        done();
      },
      selectionChangeChild(list) {
        this.selectionList = list;
      },
      selectionClearChild() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChangeChild(currentPage) {
        this.pageChild.currentPage = currentPage;
      },
      sizeChangeChild(pageSize) {
        this.pageChild.pageSize = pageSize;
      },
      refreshChangeChild() {
        this.onLoadChild(this.pageChild, this.query);
      },
      onLoadChild(page, params = {}) {
        this.loadingChild = true;
        params.groupId = this.parentId;
        getUserList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.pageChild.total = data.total;
          this.dataChild = data.records;
          this.dataChild.forEach(item => {
            item.isHandler = item.isHandler == 1;
          })
          this.loadingChild = false;
          this.selectionClearChild();
        });
      }
    }
  };
</script>

<style>
</style>
