<template>
  <!-- 
    普通查询表格
    v 1.2
    2021-04-30
    Lufthafen
  -->
  <a-card :bordered="false" class="mb-none">
    <yo-table
      :auto-load="false"
      :columns="columns"
      :load-data="loadData"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: (keys) => selectedRowKeys = keys }"
      @query="onQuery"
      @resetQuery="onResetQuery"
      ref="table"
    >
      <Auth auth="houseSelector:selectedPage" slot="query">
        <!-- 此处添加查询表单控件 -->
        <!-- ... -->
        <a-form-model-item>
          <a-range-picker v-model="query.createdTime"></a-range-picker>
        </a-form-model-item>
        <a-form-model-item label="编号">
          <a-input-number
            :formatter="(number) => number && `000${number}`.slice(-3)"
            :max="999"
            :min="1"
            :precision="0"
            :step="1"
            placeholder="请输入房屋序号"
            v-model="query.no"
          />
        </a-form-model-item>
        <a-form-model-item label="房屋性质">
          <a-radio-group @change="onChangeQueryType" button-style="solid" v-model="query.type">
            <a-radio-button value>全部</a-radio-button>
            <a-radio-button
              :key="item.code"
              :value="item.code"
              v-for="item in codes.type"
            >{{item.value}}</a-radio-button>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="行业" v-if="query.type == 2">
          <a-select class="w-150" placeholder="请选择行业" v-model="query.industry">
            <a-select-option
              :key="item.code"
              :value="+item.code"
              v-for="item in codes.industry"
            >{{item.value}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="地址">
          <a-input placeholder="请输入地址" v-model="query.address" />
        </a-form-model-item>
        <a-form-model-item label="房屋唯一编码">
          <a-input placeholder="请输入房屋唯一编码" v-model="query.houseCode" />
        </a-form-model-item>
      </Auth>
      <Auth auth="houseSelector:revoke" slot="operator">
        <a-popconfirm
          :disabled="!selectedRowKeys.length"
          @confirm="onHouseSelectRevoke"
          placement="bottomLeft"
          title="是否确认撤销"
        >
          <a-button :disabled="!selectedRowKeys.length" :loading="saving" type="danger">撤销</a-button>
        </a-popconfirm>
      </Auth>
      <!-- 格式化字段内容 -->
      <!-- ... -->
      <template slot="houseCode" slot-scope="text, record">
        <span>{{`${record.areaName}-${record.roadName}-${record.commName}-${record.note}-${`000${record.no}`.slice(-3)}`}}</span>
      </template>
      <template slot="type" slot-scope="text, record">
        <span>{{bindCodeValue(text, 'type') + (text === 2 ? `(${bindCodeValue(record.industry, 'industry')})` : '')}}</span>
      </template>
    </yo-table>
  </a-card>
</template>
<script>
/* 在此管理整个页面需要的接口名称 */
const api = {
  page: 'houseSelectedPage',
  /* ... */
};

export default {
  props: ['userId'],

  data() {
    return {
      api,

      /* 查询条件 */
      query: {
        type: '',
      },

      queryType: {
        type: '=',
        createdTime: ['>=', '<'],
      },

      /* 表格字段 */
      columns: [
        {
          title: '房屋编码',
          dataIndex: 'houseCode',
          sorter: true,
          scopedSlots: { customRender: 'houseCode' },
          width: 300,
        },
        {
          title: '房屋性质及行业',
          dataIndex: 'type',
          sorter: true,
          scopedSlots: { customRender: 'type' },
          width: 150,
        },
        {
          title: '地址',
          dataIndex: 'address',
          sorter: true,
        },
        {
          title: '登记时间',
          dataIndex: 'createdTime',
          sorter: true,
          width: 150,
        },
      ],

      /* 字典编码储存格式 */
      codes: {
        type: [],
        industry: [],
      },

      options: {},

      selectedRowKeys: [],

      saving: false,
    };
  },

  async created() {
    /** 按需加载字典编码 */
    await this.onLoadCodes();
    this.onQuery();
  },
  methods: {
    /**
     * 必要的方法
     * 传给yo-table以示意数据接口及其参数和返回的数据结构
     */
    loadData(params) {
      const query = this.$_.cloneDeep(this.query);
      const searchInfo = this.$getSearchInfo({
        query,
        queryType: this.queryType,
      });

      return this.$api[api.page]({
        ...params,
        userId: this.userId,
        searchInfo,
      }).then((res) => {
        return res.data;
      });
    },

    /**
     * 有查询功能时的必要方法
     * 加载数据时初始化分页信息
     */
    onQuery() {
      this.$refs.table.onReloadData(true);
    },

    /**
     * 有查询功能时的必要方法
     * 重置查询条件
     */
    onResetQuery() {
      /** 在这里重置查询条件时,可对特殊的字段做保留处理 */
      this.query = {
        type: 0,
      };
      this.onQuery();
    },

    /**
     * 必要方法
     * 重新列表数据
     */
    onReloadData() {
      this.$refs.table.onReloadData();
    },

    /**
     * 必要方法
     * 加载字典数据
     * 如果不需要获取相应的字典数据,此方法内容可空
     */
    onLoadCodes() {
      return this.$api
        .sysDictTypeDropDowns({ code: ['dic_house_type', 'dic_house_industry'] })
        .then(({ data: { dic_house_type, dic_house_industry } }) => {
          this.codes.type = dic_house_type;
          this.codes.industry = dic_house_industry;
        });
    },

    /**
     * 必要方法
     * 绑定数据字典值
     */
    bindCodeValue(code, name) {
      const c = this.codes[name].find((p) => p.code == code);
      if (c) {
        return c.value;
      }
      return null;
    },

    /**
     * 必要方法
     * 从列表页调用窗口的打开方法
     */
    onOpen(record) {
      this.openContentWindow({
        key: record ? record.id : 'business/house/code/form',
        title: record ? '修改房屋编码' : '新增房屋编码',
        subTitle:
          record &&
          `${record.areaName}-${record.roadName}-${record.commName}-${record.note}-${`000${record.no}`.slice(-3)}`,
        path: 'business/house/code/form',
        param: {
          record,
        },
      });
    },

    /**
     * 必要方法
     * 可以用做一系列操作的公共回调,此方法中会重新加载当前列表
     */
    onResult(success, successMessage) {
      if (success) {
        this.$message.success(successMessage);
        this.onReloadData();
      }
    },

    /**
     * 必要方法
     * 删除时调用
     */
    onDelete(record) {
      this.$refs.table.onLoading();
      this.$api[api.delete](record)
        .then(({ success }) => {
          this.onResult(success, '删除成功');
        })
        .finally(() => {
          this.$refs.table.onLoaded();
        });
    },

    onChangeQueryType() {
      if (this.query.type < 2 && this.query.hasOwnProperty('industry')) {
        this.$delete(this.query, 'industry');
      }
    },

    onHouseSelectRevoke() {
      this.saving = true;
      this.$refs.table.onLoading();
      this.$api
        .houseSelectRevoke({ ids: this.selectedRowKeys, userId: this.userId })
        .then(({ success }) => {
          this.$message.success('选房成功');
        })
        .finally(() => {
          this.saving = false;
          this.selectedRowKeys = [];
          this.$emit('reload-all');
        });
    },
  },
};
</script>