<template>
  <div>
    <div class="dm-wrap">
      <div class="top">
        <div class="left">
          <el-input v-model="search.departName" placeholder="请输入部门名称" prefix-icon="el-icon-search" style="width: 260px" clearable @change="onSearch" />
          <el-select v-model="search.status" placeholder="全部状态" class="w160" @change="onSearch" clearable>
            <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </div>
        <div class="right">
          <el-button v-if="$getButtonLimit($buttonCode.marketingAddAccountDepart)" :limit-code="$buttonCode.marketingAddAccountDepart" type="primary" @click="addDepartDialog.visible = true">增加独立计费部门</el-button>
        </div>
      </div>
      <div class="content mt20">
        <el-table :data="tableData.data" v-loading="loading" :row-style="rowStyle">
          <el-table-column v-for="(v, i) in tableData.header" :key="i" :prop="v.prop" :min-width="v.minWidth" :label="v.label" :formatter="v.formatter" :fixed="v.fixed" show-overflow-tooltip :render-header="onRender">
            <template slot-scope="scope">
              <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
              <span v-else>{{ scope.row[v.prop] || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="130">
            <template slot-scope="{ row }">
              <el-button v-if="$getButtonLimit($buttonCode.marketingAccountDetailRecord)" :limit-code="$buttonCode.marketingAccountDetailRecord" type="text" @click="toRecord(row)">记录</el-button>
              <template v-if="row.accountDepartId != 1 && $getButtonLimit($buttonCode.marketingUpdateStatus)">
                <el-button type="text" v-if="row.status == 0" :limit-code="$buttonCode.marketingUpdateStatus" @click="updateStatus(row, 'open')">启用</el-button>
                <el-button type="text" v-if="row.status == 1" :limit-code="$buttonCode.marketingUpdateStatus" @click="updateStatus(row, 'freeze')">停用</el-button>
              </template>
              <el-button v-if="$getButtonLimit($buttonCode.marketingShowStore) && row.status == 1" :limit-code="$buttonCode.marketingShowStore" type="text" @click="showStore(row)">查看门店</el-button>
            </template>
          </el-table-column>
        </el-table>
        <dm-pagination background class="dm-pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="tableData.currentPage" :page-sizes="tableData.pageSizeList" :page-size="tableData.pageSize" layout="total, sizes, prev, pager, next" :total="tableData.total" hide-on-single-page />
      </div>
    </div>
    <add-depart :visible.sync="addDepartDialog.visible" @saved="resetData" />
    <view-store :visible.sync="viewStoreDialog.visible" :depart-id="viewStoreDialog.departId" :depart-list="viewStoreDialog.departList" />
  </div>
</template>

<script>
import { formatDateTimeByType } from '@/utils/index.js';
import { getDepartList, updateDepartStatus, getDepartSum } from '@/service/api/rechargeApi.js';
import tip from '@/components/tip';
import viewStore from './components/view-store.vue';
import AddDepart from './components/add-depart.vue';
export default {
  name: 'detail-table',
  components: { tip, AddDepart, viewStore },
  data() {
    return {
      search: {
        departName: '',
        status: null
      },
      tableData: {
        data: [],
        currentPage: 1,
        pageSizeList: [20, 40, 60, 80],
        pageSize: 20,
        header: [],
        total: 0,
        sum: {}
      },
      loading: false,
      addDepartDialog: {
        visible: false
      },
      viewStoreDialog: {
        visible: false,
        departId: '',
        departList: []
      },
      statusList: [
        { label: '启用', value: 1 },
        { label: '停用', value: 0 }
      ]
    };
  },
  async created() {
    this.getTableHeader();
    this.resetData();
    this.$store.commit('mutations_breadcrumb', [
      { name: '企业管理', path: '' },
      { name: '计费中心', path: '/recharge/board' },
      { name: '账户明细', path: '' }
    ]);
  },
  mounted() {
    this.$store.commit(
      'mutations_layoutTips',
      `<div class="layout--tips" style="display: flex">
          <i class="iconfont icon-warning-circle-fill" style="margin-top: -3px"></i>
          <div class="ml5">
           “多账户模式”下，系统将根据所配置的计费规则将通讯费用按照下方的“独立计费部门”进行汇总核算及扣除费用：<br />
            1、计费规则中：费用由“会员所属服务门店”、“导购所在门店”承担时，最终都会根据门店所属的“独立计费部门”进行汇总核算和扣除，若产生费用时会员无服务门店，则由总部承担费用；<br />
            2、计费规则中：费用由“活动创建人”承担时，会根据该管理员所属的“独立计费部门”进行汇总核算和扣除；<br />
            注意：若管理员或门店所归属的部门未被设置为“独立计费部门”，则系统将依次向其上级部门查询是否被设置为独立计费部门，查询不到则记录到“企业总部”账上；
          </div>
      </div>`
    );
  },
  beforeDestroy() {
    this.$store.commit('mutations_layoutTips', '');
  },
  methods: {
    // table-methods
    async getSumData() {
      const { result } = await getDepartSum();
      this.tableData.sum = result;
      return true;
    },
    async getTableData() {
      this.loading = true;
      const para = {
        searchParams: this.search.departName,
        status: [0, 1].includes(this.search.status) ? this.search.status : -1,
        pageSize: this.tableData.pageSize,
        currentPage: this.tableData.currentPage
      };
      const { result } = await getDepartList(para);
      this.tableData.data = result.result || [];
      this.tableData.data.unshift(this.tableData.sum);
      this.tableData.total = result.totalCount;
      this.loading = false;
    },
    getTableHeader() {
      this.tableData.header = [
        {
          label: { name: '独立计费部门' },
          prop: 'accountDepartName',
          minWidth: 120
        },
        {
          label: { name: '上级部门' },
          prop: 'parentDepartName',
          minWidth: 120
        },
        {
          label: { name: '计费门店数', tipText: '由此“独立计费部门”统一核算费用的门店数，若当前部门的某下级部门被设置为了独立计费部门并且为启用状态，则此处将不包含下级部门的门店数' },
          prop: 'storeCount',
          minWidth: 120,
          formatter: row => row.storeCount || 0
        },
        {
          label: { name: '账户余额(元)' },
          prop: 'accountFunds',
          minWidth: 120,
          formatter: row => (row.accountFunds ? parseFloat(row.accountFunds).toFixed(2) : '0.00')
        },
        {
          label: { name: '添加时间' },
          prop: 'createTime',
          minWidth: 120,
          formatter: row => (row.createTime ? formatDateTimeByType(row.createTime, 'yyyy-MM-dd HH-mm-ss') : '--')
        }
      ];
    },
    handleSizeChange(val) {
      this.tableData.pageSize = val;
      this.tableData.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.tableData.currentPage = val;
      this.getTableData();
    },
    // 渲染表头icon
    onRender(h, { column }) {
      let isShowTip = column.label.name == '计费门店数';
      return h('span', [
        h('span', column.label.name),
        h(isShowTip && tip, {
          props: { text: column.label.tipText }
        })
      ]);
    },
    async updateStatus(row, type) {
      const open = { successBtn: '确认启用', title: '确认启用吗？', info: '启用后，该部门下的管理员或门店所产生的通讯费用将由该部门承担（启用前已产生的通讯费用归属不会变更）', status: 1, successMsg: '启用成功' };
      const freeze = { successBtn: '确认停用', title: '确认停用吗？', info: '停用后，该部门将不再独立计费（历史已产生的费用归属不会变更）。后续新产生的费用系统将依次向其上级部门查询是否被设置为独立计费部门，查询不到则记录到“企业总部”账上', status: 0, successMsg: '停用成功' };
      const opt = type == 'open' ? open : freeze;
      try {
        const options = { confirmButtonText: opt['successBtn'], cancelButtonText: '取消', type: 'warning' };
        await this.$confirm(opt['info'], opt['title'], options);
        await updateDepartStatus({ status: opt['status'], accountDepartId: row.accountDepartId });
        this.$message.success(opt['successMsg']);
        this.resetData();
      } catch (e) {
        return false;
      }
    },
    showStore(row) {
      this.viewStoreDialog.departList = row.accountEnterpriseDpartmentList;
      this.viewStoreDialog.departId = row.departmemtId;
      this.viewStoreDialog.visible = true;
    },
    toRecord(row) {
      this.$router.push(`/recharge/record?id=${row.accountDepartId}`);
    },
    rowStyle({ row, rowIndex }) {
      return rowIndex == 0 && { background: '#eef4ff' };
    },
    onSearch() {
      this.tableData.currentPage = 1;
      this.getTableData();
    },
    async resetData() {
      await this.getSumData();
      this.getTableData();
    }
  },
  computed: {
    // do something
  },
  watch: {
    // do something
  }
};
</script>

<style scoped lang="scss">
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
