<template>
  <ifbp-page class="distribution-container">
    <ifbp-button-area id="search-container">
      <!-- <el-input
        class="filter-input"
        slot="left"
        v-model="filterStr"
        @change="filterStrChange"
        placeholder="输入内容对表格进行筛选">
      </el-input> -->
      <div class="fr">
        <el-input
          class="filter-input"
          v-model="filterStr"
          icon="search"
          :on-icon-click="searchTriggered"
          @keyup.enter="searchTriggered"
          placeholder="角色名称/角色编码/配置名称/配置编码">
        </el-input>
      </div>
    </ifbp-button-area>

    <ifbp-main-area>
      <div class="select-area">
        <el-select
          v-if="Array.isArray(layoutList) && layoutList.length"
          class="layout-select"
          v-model="currentLayoutId"
          placeholder="-- 请选择页面布局 --"
          :disabled="!Array.isArray(selectedRows) || !selectedRows.length"
          @change="layoutChange">
          <el-option label="系统级页面" value="fe_reset"></el-option>
          <el-option
            v-for="(layout, layoutIndex) in layoutList"
            :key="layoutIndex"
            :label="layout.page_config_name + ' ' + layout.page_config_code"
            :value="layout.page_config_id">
          </el-option>
        </el-select>
        <span class="status-count">{{ '已选取 ' + selectedCount }}</span>
        <span class="status-count">{{ '已更改 ' + updatedCount }}</span>
      </div>
      <!-- user layout table -->
      <el-table
        ref="userLayoutTable"
        :data="tableData"
        border
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="tableSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="角色"
          max-width="30%"
          prop="role_name">
        </el-table-column>
        <el-table-column
          label="页面布局"
          prop="layoutName"
          show-overflow-tooltip>
        </el-table-column>
      </el-table>

      <!-- pagination -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalElements">
      </el-pagination>
    </ifbp-main-area>

    <ifbp-footer v-if="updatedCount && selectedCount">
      <el-button type="default" @click="cancelChange">取消</el-button>
      <el-button class="fr" type="primary" @click="saveChange">保存</el-button>
    </ifbp-footer>
  </ifbp-page>
</template>
<script>
export default {
  data() {
    return {
      // 当前选中行
      selectedRows: null,
      // 过滤文字
      filterStr: null,
      // table 数据
      tableData: null,
      // 布局下拉框数据
      layoutList: null,
      // 当前选中的 layout id
      currentLayoutId: null,
      // 已改变
      updatedCount: 0,
      /**
       * pagination
       */
      totalElements: 0,
      currentPage: 1,
      pageSize: 10,
    }
  },
  props: {
    pageConfigHeadId: {
      type: String
    }
  },
  computed: {
    // 筛选
    // filteredData() {
    //   if (!Array.isArray(this.tableData)) {
    //     return [];
    //   }
    //   const filterStr = this.filterStr;
    //   if (!filterStr) {
    //     return this.tableData;
    //   }
    //   const filteredArr = this.tableData.filter(role => {
    //     if (role.role_name && role.role_name.indexOf(filterStr) !== -1) {
    //       return true;
    //     }
    //     if (role.role_code && role.role_code.indexOf(filterStr) !== -1) {
    //       return true;
    //     }
    //     if (role.layoutName && role.layoutName.indexOf(filterStr) !== -1) {
    //       return true;
    //     }
    //     return false;
    //   });
    //   return filteredArr;
    // },
    selectedCount() {
      return Array.isArray(this.selectedRows) ? this.selectedRows.length : 0;
    }
  },
  methods: {
    // 请求数据
    request() {
      this.getLayoutList();
    },
    // 获取下拉选项
    getLayoutList() {
      const requestUrl = '/ifbp-app-sm-infoset-web/page_config_role/getPageConfigByHeadId';
      const requestData = this.pageConfigHeadId;
      this.$http({
        url: requestUrl,
        method: 'post',
        data: requestData,
        dataType: 'json',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          const resData = res.data;
          if (resData.success) {
            const layoutData = resData.data
            this.layoutList = layoutData;
            // 回调中获取 table data
            if (Array.isArray(layoutData) && layoutData.length) {
              this.getTableData();
            }
          } else if (layoutData.error && resData.error.errorMessage) {
            console.log('信息获取失败', JSON.stringify(resData.error));
            this.$message({
              message: '信息获取失败: ' + resData.error.errorMessage,
              type: 'error'
            });
          }
        })
        .catch((e) => {
          this.$message({
            message: '请求失败:' + JSON.stringify(e),
            type: 'error'
          });
        });
    },
    // 获取 table 数据
    getTableData() {
      // const requestUrl = '/ifbp-app-sm-infoset-web/page_config_role/getPageConfigRoleByHeadId';
      // const requestData = this.pageConfigHeadId;
      // reset data
      // this.cancelChange();
      const requestUrl = '/ifbp-app-sm-infoset-web/page_config_role/queryPageConfigRole';
      let requestData = {
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize,
        searchParams: {
          searchMap: {
            page_config_head_id: this.pageConfigHeadId
          }
        }
      };
      if (this.filterStr) {
        requestData.searchParams.searchMap.keyword = this.filterStr;
      }

      this.$http({
        url: requestUrl,
        method: 'post',
        data: requestData,
        dataType: 'json',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(res => {
          const resData = res.data;
          if (resData.success) {
            const formatedTableData = this.addLayoutNameForTableItem(resData.data.content);
            this.tableData = formatedTableData;
            this.totalElements = resData.data.totalElements;
          } else if (resData.error && resData.error.errorMessage) {
            console.log('信息获取失败', JSON.stringify(resData.error));
            this.$message({
              message: '信息获取失败: ' + resData.error.errorMessage,
              type: 'error'
            });
          }
        })
        .catch((e) => {
          console.log('请求失败:', JSON.stringify(e));
          this.$message({
            message: '请求失败:' + JSON.stringify(e),
            type: 'error'
          });
        });
      // const formatedTableData = this.addLayoutNameForTableItem(MockData.userLayoutList);
      // console.log(JSON.stringify(formatedTableData));
      // this.tableData = formatedTableData;
    },
    resetTableData() {
      // this.tableData = JSON.parse(JSON.stringify(this.copiedTaleData));
      if (this.$refs.userLayoutTable) {
        this.$refs.userLayoutTable.clearSelection();
      }
      this.updatedCount = 0;
      if (!Array.isArray(this.tableData)) {
        return;
      }
      this.tableData.forEach(user => {
        user.page_config_id = user.originLayoutId;
        user.layoutName = user.originLayoutName;
      });
    },
    // add layout name field for each row of table data && save original layout id for each row
    addLayoutNameForTableItem(userList) {
      if (!Array.isArray(userList) || !userList.length) {
        return [];
      }
      const layouts = this.layoutList;
      userList.forEach(user => {
        for (let i = 0; i < layouts.length; i++) {
          const layout = layouts[i];

          // 假数据需要给 page config id 随机赋值
          // const testArr = ['OID10000000sythhh', 'OID10000000syt666', 'wbalone10000000twe1'];
          if (!user.page_config_id) {
            // user.page_config_id = testArr[Math.floor(Math.random() * testArr.length)];
            // console.log('****** mock page config id: ', user.page_config_id);
            user.layoutName = '系统级页面';
            user.originLayoutId = null;
            user.originLayoutName = '系统级页面';
          } else if (user.page_config_id === layout.page_config_id) {
            user.layoutName = layout.page_config_name + ' ' + layout.page_config_code;
            user.originLayoutId = layout.page_config_id;
            user.originLayoutName = layout.page_config_name + ' ' + layout.page_config_code;
          }
        }
      });
      return userList;
    },
    // select change
    layoutChange(val) {
      if (!val) {
        return;
      }
      if (!this.selectedCount) {
        return;
      }
      let currentLayoutName;
      if (val === 'fe_reset') {
        currentLayoutName = '系统级页面';
      } else {
        const layouts = this.layoutList;
        for (let i = 0; i < layouts.length; i++) {
          const layout = layouts[i];
          if (val === layout.page_config_id) {
            currentLayoutName = layout.page_config_name + ' ' + layout.page_config_code;
            break;
          }
        }
      }
      if (currentLayoutName === undefined) {
        return;
      }
      // set layout info for selected rows
      const selectedRows = this.selectedRows;
      let updatedCount = 0;
      this.selectedRows.forEach(row => {
        if (row.page_config_id !== val) {
          row.page_config_id = (val === 'fe_reset' ? null : val);
          row.layoutName = currentLayoutName;
        }
        if (row.originLayoutName !== currentLayoutName) {
          updatedCount++;
        }
      });
      this.updatedCount = updatedCount;
    },
    // table selection change
    tableSelectionChange(val) {
      this.selectedRows = val;
      this.currentLayoutId = null;
    },
    // 筛选条件改变
    filterStrChange() {
    // 清空 table 选中项
      this.$refs.userLayoutTable.clearSelection();
    },
    // 点击保存
    saveChange() {
      const requestUrl = '/ifbp-app-sm-infoset-web/page_config_role/savePageConfigRole';
      let roleLayoutArr = [];
      this.selectedRows.forEach(role => {
        roleLayoutArr.push({
          'id': role.id,
          'page_config_id': role.page_config_id,
          'role_id': role.role_id
        });
      });
      const requestData = {
        pageConfigRoleList: roleLayoutArr,
        'page_config_head_id': this.pageConfigHeadId
      };
      this.$http({
        url: requestUrl,
        method: 'post',
        data: requestData,
        dataType: 'json'
      })
        .then(res => {
          const resData = res.data;
          if (resData.success) {
            this.tableData = this.addLayoutNameForTableItem(this.tableData);
            this.resetTableData();
            this.$message('保存成功！');
            this.$emit('successfullySaved');
          } else if (resData.error && resData.error.errorMessage) {
            console.log('保存失败', JSON.stringify(resData.error));
            this.$message({
              message: '保存失败: ' + resData.error.errorMessage,
              type: 'error'
            });
          }
        })
        .catch((e) => {
          console.log('请求失败:', JSON.stringify(e));
          this.$message({
            message: '请求失败:' + JSON.stringify(e),
            type: 'error'
          });
        });
    },
    // 点击取消
    cancelChange() {
      // this.filterStr = null;
      this.resetTableData();
    },

    /**
     * pagination
     */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTableData();
    },
    searchTriggered() {
      this.currentPage = 1;
      this.getTableData();
    }
  },
  created() {
    if (!this.pageConfigHeadId) {
      this.$message({
        message: '请传入 pageConfigHeadId',
        type: 'error'
      });
      return;
    }
    this.request();
  }
}
</script>
<style scoped>
  .filter-input,
  .layout-select {
    width: 240px;
  }
  .status-count {
    line-height: 32px;
    margin-left: 12px;
  }
  .select-area {
    margin-bottom: 16px;
  }
</style>
<style>
  .distribution-container .list-main-container {
    margin-top: 0;
  }
</style>
