<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="smUserList"
      @row-click="changeSelection"
      @selection-change="handleSelectionChange"
      @sort-change="onSortChange"
      :default-sort="defaultSort"
    >
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
          :key="column.key"
          :label="column.label"
          :prop="column.key"
          :align="column.align"
          :min-width="column.minWidth"
          :sort-orders="['ascending', 'descending', null]"
          :sortable="column.sortable"
          :show-overflow-tooltip="column.overflow"
          :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'type'">
              <dict-tag :value="d.row.type" :options="dict.type.user_type"/>
            </template>
            <template v-else-if="column.key === 'phonenumber'">
              <user-link :id="d.row.userId" :name="d.row.phonenumber"/>
            </template>
            <template v-else-if="column.key === 'userName'">
              <user-link :id="d.row.userId" :name="d.row.realOrUserName"/>
            </template>
            <template v-else-if="column.key === 'referenceId'">
              <user-link :id="d.row.referenceId" :name="d.row.referenceName"/>
            </template>
            <template v-else-if="column.key === 'agentId'">
              <user-link :id="d.row.agentId" :name="d.row.agentName"/>
            </template>
            <template v-else-if="column.key === 'point'">
              {{d.row.point | money | defaultValue}} %
            </template>
            <template v-else-if="column.key === 'storeCount'">
              {{d.row.storeCount | defaultValue}} 家
            </template>
            <template v-else-if="column.key === 'deviceCount'">
              {{d.row.deviceCount | defaultValue}} 台
            </template>
            <template v-else-if="column.key === 'billCount'">
              {{d.row.billCount | defaultValue}} 单
            </template>
            <template v-else-if="['investorCount', 'bizManCount', 'agentCount'].includes(column.key)">
              {{d.row[column.key] | defaultValue}} 人
            </template>
            <template v-else-if="['billAmount', 'provideBonus'].includes(column.key)">
              {{d.row[column.key] | money | defaultValue}} 元
            </template>
            <template v-else-if="column.key === 'deviceAdmin'">
              <el-tag :type="d.row.deviceAdmin ? 'danger' : 'info'">{{d.row.deviceAdmin ? '是' : '否'}}</el-tag>
            </template>
            <template v-else>
              {{d.row[column.key] | defaultValue}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSee(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { $serviceType, $showColumns, $withdrawServiceType } from '@/utils/mixins'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import UserInput from '@/components/Business/SmUser/UserInput.vue'
import DeptTreeSelect from '@/components/Business/Dept/DeptTreeSelect.vue'
import { FieldName, SmUserType } from '@/utils/constants'
import { mapGetters } from 'vuex'
import { agentListAgent, agentListBiz, agentListInvestor } from '@/api/agent/user'
import { bizListBiz, bizListInvestor } from '@/api/biz/user'

const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "MchUser",
  mixins: [$showColumns, $serviceType, $withdrawServiceType],
  dicts: ['user_type', 'sys_user_sex', 'service_type', 'withdraw_service_type'],
  components: { DeptTreeSelect, UserInput, UserLink },
  props: {
    query: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    isEdit() {
      return this.form != null && this.form.userId != null;
    },
    FieldName() {
      return FieldName
    },
    ...mapGetters(['deptId', 'smUserType']),
    SmUserType() {
      return SmUserType
    },
    rules() {},
    // 列表API
    listApi() {
      // 代理商视角
      if (this.smUserType === SmUserType.AGENT) {
        if (this.type === SmUserType.AGENT) {
          return agentListAgent;
        } else if (this.type === SmUserType.BIZ) {
          return agentListBiz;
        } else if (this.type === SmUserType.INVESTOR) {
          return agentListInvestor;
        }
      }
      // 业务员视角
      else if (this.smUserType === SmUserType.BIZ) {
        if (this.type === SmUserType.BIZ) {
          return bizListBiz;
        } else if (this.type === SmUserType.INVESTOR) {
          return bizListInvestor;
        }
      }
    }
  },
  data() {
    return {
      defaultSort,
      type: null, // 用户类型
      span: 12,
      columns: [
        {key: 'userName', visible: true, label: '用户名称', align: 'center', minWidth: null, sortable: false, width: "120"},
        {key: 'phonenumber', visible: true, label: '手机号码', align: 'center', minWidth: null, sortable: true, width: "120"},
        {key: 'type', visible: true, label: '角色', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'point', visible: true, label: '分成', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'referenceId', visible: true, label: '推广人', align: 'center', minWidth: null, sortable: true, width: null},
        // {key: 'status', visible: true, label: '状态', align: 'center', minWidth: null, sortable: true, width: null},
        // {key: 'createTime', visible: true, label: '注册时间', align: 'center', minWidth: null, sortable: true, width: "100"},
        {key: 'agentCount', visible: true, label: `${FieldName.AGENT}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'bizManCount', visible: true, label: `${FieldName.BIZ}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'investorCount', visible: true, label: `${FieldName.INVESTOR}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'storeCount', visible: true, label: `${FieldName.STORE}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deviceCount', visible: true, label: '设备数', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'billCount', visible: true, label: '订单数', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'billAmount', visible: true, label: '订单总额', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'provideBonus', visible: true, label: '提供分成', align: 'center', minWidth: null, sortable: false, width: null},
      ],
      openServiceRate: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 普通用户信息表格数据
      smUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        phonenumber: null,
        serviceType: null,
        status: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }

    if (this.$route.meta.userType) {
      this.type = this.$route.meta.userType;
    }
    if (this.query.type) {
      this.type = this.query.type;
    }

    this.initColumn(this.type);
    this.getList();
  },
  methods: {
    // 初始化列
    initColumn(type) {
      if (type === SmUserType.INVESTOR) {
        this.removeColumn(['agentCount', 'bizManCount','investorCount'])
      } else if (type === SmUserType.BIZ) {
        this.removeColumn(['agentCount'])
      }
    },
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    // 更换某一行的选中状态
    changeSelection(row){
      if (this.ids.includes(row.userId)){
        this.$refs.table.toggleRowSelection(row, false);
        this.ids = this.ids.filter(i => i !== row.userId);
      }else {
        this.$refs.table.toggleRowSelection(row, true);
        this.ids.push(row.ids);
      }
    },
    /** 查询普通用户信息列表 */
    getList() {
      this.loading = true;
      this.listApi(this.queryParams).then(res => {
        this.smUserList = res.rows;
        this.total = res.total;
        this.loading = false;
      }).finally(() => {
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        userName: null,
        nickName: null,
        phonenumber: null,
        sex: "2",
        avatar: null,
        isMch: false,
        deviceAdmin: false,
        serviceType: '1',
        type: this.type,
        deptId: this.deptId,
        point: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleSee(row) {
      this.$router.push({path: `/user/${row.userId}`})
    },
  }
};
</script>
