<template>
  <basic-container>

    <el-tabs :value="level" @tab-click="handleClickType">
      <el-tab-pane></el-tab-pane>
      <el-tab-pane label="全局设置" name="1">
        <div v-if="activeTab == '1'">
          <avue-crud :option="option"
                     :table-loading="loading"
                     :data="data"
                     :page="page"
                     :permission="permissionList"
                     ref="crud"
                     @search-change="searchChange"
                     @search-reset="searchReset"
                     @selection-change="selectionChange"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     @refresh-change="refreshChange"
                     @on-load="onLoad">
            <template slot="menuLeft">
              <el-button type="danger" v-if="permission.alarmsetting_add" plain size="small" @click="init(row, true)">初始化数据</el-button>
            </template>
            <template slot="isNotice" slot-scope="{row}">
              <el-switch v-model="row.isNotice" :disabled="!permission.alarmsetting_edit" @change="changeNotice(row)">
              </el-switch>
            </template>
          </avue-crud>
        </div>
      </el-tab-pane>
      <el-tab-pane label="小区设置" name="2">
        <div v-if="activeTab == '2'">
          <avue-crud :data="xqSettingData" :option="xqOption"
                     :page="xqpage"
                     v-model="form"
                     :before-open="beforeOpen"
                     @row-update="rowUpdate"
                     @row-save="rowSave"
                     @row-del="rowDel"
                     @current-change="currentChangeXq"
                     @size-change="sizeChangeXq"
                     @refresh-change="refreshChangeXq"
                     @on-load="loadXqSetting"
          >
            <template slot="menuLeft">
              <div style="display: flex;">
                <el-select filterable v-model="selectXqId" size="small" placeholder="请选择" @change="selectResidential">
                  <el-option
                    v-for="(item, idx) in ytXqList"
                    :key="idx"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button type="danger" style="margin-left: 20px;" v-if="permission.alarmdirector_add && ytXqList.length > 0" plain size="small" @click="initXqSetting">初始化告警设置</el-button>
                <el-button type="primary" style="margin-left: 20px;" v-if="permission.alarmdirector_add && ytXqList.length > 0" plain size="small" @click="settingDirector">告警负责人</el-button>
              </div>

            </template>

            <template slot="isNotice" slot-scope="{row}">
              <el-switch v-model="row.isNotice" :disabled="!permission.alarmsetting_edit" @change="changeNotice(row)">
              </el-switch>
            </template>
            <template slot="isGenerateJob" slot-scope="{row}">
              <el-switch v-model="row.isGenerateJob" :disabled="!permission.alarmsetting_edit" @change="changeGenerateJob(row)">
              </el-switch>
            </template>
          </avue-crud>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog :modal-append-to-body="false" append-to-body :visible.sync="directorVisible" title="告警负责人" top="2vh" center width="70%" height="80%">
      <alarm-director v-if="directorVisible" :residential-id="selectXqId"></alarm-director>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, initData, initDataWithResidential, getAlarmTypeSelect} from "@/api/device/elevatoralarmsetting";
  import {mapGetters} from "vuex";
  import {getListWithYtelevatorXq} from "@/api/device/elevatordevice";
  import AlarmDirector from "./elevatoralarmdirector";

  export default {
    components: {AlarmDirector},
    data() {
      return {
        ytXqList: [],
        selectXqId: '',
        activeTab: '1',
        directorVisible: false,

        form: {},
        query: {},
        loading: true,
        level: "1",
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 220,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: false,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          menu: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "电梯告警类型",
              prop: "alarmType",
            },
            {
              label: "电梯告警名称",
              prop: "alarmName",
            },
            {
              label: "是否开启告警通知",
              prop: "isNotice",
              type:'switch',
              slot: true,
              // cell: true
            },
          ]
        },
        data: [],
        xqquery: {},
        xqform: {},
        xqpage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        xqselectionList: [],
        xqSettingData: [],
        xqOption: {
          height:'auto',
          calcHeight: 220,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: false,
          addBtn: true,
          menu: true,
          editBtn: false,
          delBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "小区名称",
              prop: "residentialName",
              addDisplay: false,
            },
            {
              label: "告警类型",
              prop: "alarmType",
              type: "select",
              dicData: [],
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "告警名称",
              prop: "alarmName",
              addDisplay: false
            },
            {
              label: "开启告警通知",
              prop: "isNotice",
              type:'switch',
              slot: true,
              labelWidth: "200",
              addDisplay: false,
            },
            {
              label: "开启告警生成工单",
              prop: "isGenerateJob",
              hide: true,
              type:'switch',
              addDisplay: false,
              slot: true,
              // cell: true
            },
          ]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.alarmsetting_add, false),
          viewBtn: this.vaildData(this.permission.alarmsetting_view, false),
          delBtn: this.vaildData(this.permission.alarmsetting_delete, false),
          editBtn: this.vaildData(this.permission.alarmsetting_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      settingDirector(){
        this.directorVisible = true;
      },
      selectResidential(){
        // 加载列表
        this.loadXqSetting(this.xqpage);
        this.initAlarmTypeSelect();
      },
      initAlarmTypeSelect(){
        this.selectXqId && getAlarmTypeSelect(this.selectXqId).then(res => {
          let alarmSelect = res.data.data;
          this.xqOption.column[1].dicData = alarmSelect;
        });
      },
      initXqSetting(){
        this.selectXqId &&
        initDataWithResidential(this.selectXqId).then(() => {
          this.$message({
            type: "success",
            message: "数据初始化成功!"
          });
          // 加载列表
          this.loadXqSetting(this.xqpage);
        });
      },
      loadXqSetting(page, params = {}){
        params = {};
        this.loading = true;
        params.level = 2;
        params.residentialId = this.selectXqId;
        this.selectXqId && getList(page.currentPage, page.pageSize, Object.assign(params, this.xqquery)).then(res => {
          const data = res.data.data;
          this.xqpage.total = data.total;
          data.records.forEach(item => {
            // item.$cellEdit = false;
            item.isNotice = item.isNotice == 1;
            item.isGenerateJob = item.isGenerateJob == 1;
          })
          this.xqSettingData = data.records;
          this.loading = false;
          // this.selectionClear();
        });
      },
      handleClickType(tab){
        this.activeTab = tab.name;
        if (tab.name == '1'){
          //全局配置
        }else {
          //小区局部配置
          if (this.ytXqList.length <= 0){
            getListWithYtelevatorXq().then(res => {
              this.ytXqList = res.data.data;
              if (this.ytXqList && this.ytXqList.length > 0){
                this.selectXqId = this.ytXqList[0].id;
                this.loadXqSetting(this.xqpage);
              }
            });
          }else{
            if (this.ytXqList && this.ytXqList.length > 0){
              this.selectXqId = this.ytXqList[0].id;
              this.loadXqSetting(this.xqpage);
            }
          }

        }
      },
      init(){
        initData().then(() => {
          this.$message({
            type: "success",
            message: "数据初始化成功!"
          });
          this.onLoad(this.page)
        });
      },
      changeNotice(row) {
        row.isNotice = row.isNotice ? 1 : 0;
        if (row.level == 2){
          row.isGenerateJob = row.isGenerateJob ? 1 : 0;
        }
        update(row).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          row.level == 1 ? this.onLoad(this.page) : this.loadXqSetting(this.xqpage);
        }, error => {
          console.log(error);
        });
      },
      changeGenerateJob(row) {
        row.isNotice = row.isNotice ? 1 : 0;
        row.isGenerateJob = row.isGenerateJob ? 1 : 0;
        update(row).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.loadXqSetting(this.xqpage);
        }, error => {
          console.log(error);
        });
      },
      rowSave(row, done, loading) {
        row.alarmName = row.$alarmType;
        row.residentialId = this.selectXqId;
        row.level = 2;
        add(row).then(() => {
          this.loadXqSetting(this.xqpage);
          this.xqOption.column[1].dicData = [];
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          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.loadXqSetting(this.xqpage);
            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.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        // 初始化告警类型select(未有配置的类型)
        this.initAlarmTypeSelect();
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.xqpage, this.xqquery);
      },
      currentChangeXq(currentPage){
        this.xqpage.currentPage = currentPage;
      },
      sizeChangeXq(pageSize){
        this.xqpage.pageSize = pageSize;
      },
      refreshChangeXq() {
        this.loadXqSetting(this.xqpage, this.xqquery);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.level = 1;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          data.records.forEach(item => {
            // item.$cellEdit = false;
            item.isNotice = item.isNotice == 1;
          })
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
