<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="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="realOrUserName">
        <el-input
          v-model="queryParams.realOrUserName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择用户类型" clearable @change="handleQuery">
          <el-option v-for="item of dict.type.sm_user_type" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="帐号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择帐号状态" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.sm_user_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备服务费类型" prop="serviceType" label-width="8em">
        <el-select v-model="queryParams.serviceType" placeholder="请选择设备服务费类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.service_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提现服务费类型" prop="withdrawServiceType" label-width="8em">
        <el-select v-model="queryParams.withdrawServiceType" placeholder="请选择提现服务费类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.withdraw_service_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否管理" prop="deviceAdmin">
        <el-radio-group v-model="queryParams.deviceAdmin" @change="handleQuery">
          <el-radio :label="null">全部</el-radio>
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </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">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:smUser:add']"
        >添加用户</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:smUser:export']"
        >导出</el-button>
      </el-col>
      <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 :options="dict.type.sm_user_type" :value="d.row.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 === 'realOrUserName'">
              <user-link :id="d.row.userId" :name="d.row.realOrUserName"/>
            </template>
            <template v-else-if="column.key === 'storeCount'">
              {{d.row.storeCount | defaultValue}} 家
            </template>
            <template v-else-if="column.key === 'totalIncome'">
              {{d.row.totalIncome | money}} 元
            </template>
            <template v-else-if="column.key === 'withDrawlAmount'">
              {{d.row.withDrawlAmount | money}} 元
            </template>
            <template v-else-if="column.key === 'balance'">
              {{d.row.balance | money}} 元
            </template>
            <template v-else-if="column.key === 'waitBonusAmount'">
              {{d.row.waitBonusAmount | money}} 元
            </template>
            <template v-else-if="column.key === 'realServiceRate'">
              {{d.row.realServiceRate | money | defaultValue}} %
            </template>
            <template v-else-if="column.key === 'agentServiceRate'">
              {{d.row.agentServiceRate | money | defaultValue}} %
            </template>
            <template v-else-if="column.key === 'withdrawServiceRate'">
              <template v-if="d.row.withdrawServiceRate == null || d.row.withdrawServiceType == null">跟随渠道</template>
              <template v-else>
                <dict-tag :options="dict.type.withdraw_service_type" :value="d.row.withdrawServiceType"/>
                {{d.row.withdrawServiceRate}} {{withdrawServiceUnit(d.row.withdrawServiceType)}}
              </template>
            </template>
            <template v-else-if="column.key === 'status'">
              <dict-tag :options="dict.type.sm_user_status" :value="d.row.status"/>
            </template>
            <template v-else-if="column.key === 'deviceCount'">
              {{d.row.deviceCount | defaultValue}} 台
            </template>
            <template v-else-if="column.key === 'isReal'">
              <boolean-tag :value="d.row.isReal" true-text="已实名" false-text="未实名"/>
            </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]}}
            </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)"
            v-hasPermi="['system:smUser:detail']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:smUser:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:smUser:remove']"
          >删除</el-button>
          <el-button
            type="text"
            icon="el-icon-refresh"
            size="mini"
            @click="handleResetService(scope.row)"
            v-hasPermi="['system:smUser:edit']"
          >重置服务费</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleUpdateRisk(scope.row)"
            v-hasPermi="['system:smUser:edit']"
          >配置</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"
    />

    <!--用户设置-->
    <user-config-dialog :show.sync="showConfigDialog" :user-id="row.userId" @success="getList" show-current/>

    <!-- 添加或修改普通用户信息对话框 -->
    <user-form-dialog 
      :show.sync="open" 
      :user-id="userId" 
      @success="getList"
    />

  </div>
</template>

<script>
import {
  listSmUser,
  delSmUser,
  resetSmUserService
} from '@/api/system/smUser'
import { $serviceType, $showColumns, $withdrawServiceType } from '@/utils/mixins'
import UserLink from '@/components/Business/SmUser/UserLink.vue'
import { SmUserType } from '@/utils/constants'
import UserConfigDialog from '@/views/system/smUser/components/UserConfigDialog.vue'
import BooleanTag from '@/components/BooleanTag/index.vue'
import UserFormDialog from './components/UserFormDialog.vue'

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

export default {
  name: "SmUser",
  mixins: [$showColumns, $serviceType, $withdrawServiceType],
  components: { BooleanTag, UserConfigDialog, UserLink, UserFormDialog },
  dicts: ['sm_user_status', 'sm_user_type', 'sys_user_sex', 'service_type', 'withdraw_service_type'],
  computed: {
    SmUserType() {
      return SmUserType
    },
    serviceUnit() {
      return (type) => {
        return type === '2' ? '元' : '%';
      }
    }
  },
  data() {
    return {
      showConfigDialog: false,
      row: {},  // 当前row
      defaultSort,
      span: 12,
      columns: [
        {key: 'userId', visible: false, label: 'ID', align: 'center', minWidth: "80", sortable: true, width: null},
        {key: 'realOrUserName', visible: true, label: '名称', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'isReal', visible: true, label: '实名', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'phonenumber', visible: true, label: '手机', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'type', visible: true, label: '角色', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'appName', visible: true, label: '应用', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'remark', visible: true, label: '备注', align: 'center', minWidth: null, sortable: false, overflow: true, width: null},
        {key: 'status', visible: true, label: '状态', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'createTime', visible: false, label: '注册时间', align: 'center', minWidth: "120", sortable: true, width: "100"},
        {key: 'balance', visible: true, label: '余额', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'realServiceRate', visible: true, label: '商户服务费', align: 'center', minWidth: null, sortable: false, width: "120"},
        {key: 'agentServiceRate', visible: true, label: '代理服务费', align: 'center', minWidth: null, sortable: false, width: "120"},
        {key: 'withdrawServiceRate', visible: true, label: '提现服务费', align: 'center', minWidth: null, sortable: false, width: "120"},
        {key: 'storeCount', visible: true, label: '店铺数量', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deviceCount', visible: true, label: '设备数量', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deviceAdmin', visible: true, label: '是否管理', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'riskCount', visible: false, label: '风险次数', align: 'center', minWidth: null, sortable: true, width: "120"},
      ],
      openServiceRate: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 普通用户信息表格数据
      smUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        isMch: null,
        phonenumber: null,
        serviceType: null,
        status: null,
        realOrUserName: null,
        deviceAdmin: null
      },
      userId: null,
    };
  },
  created() {
    this.removeColumn(['status'])

    this.getList();
  },
  methods: {
    // 重置用户服务费
    handleResetService(row) {
      this.$confirm(`确认重置用户${row.phonenumber}的服务费？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        resetSmUserService(row.userId).then(res => {
          if (res.code === 200) {
            this.$message.success("重置成功");
          }
        }).finally(() => {
          this.getList();
        })
      })
    },
    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;
      listSmUser(this.queryParams).then(response => {
        this.smUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.userId = null;
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 查看按钮操作 */
    handleSee(row) {
      this.$router.push({path: `/smUser/user/${row.userId}`})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.userId = row.userId || this.ids;
      this.open = true;
      this.title = "修改用户信息";
    },
    handleUpdateRisk(row) {
      this.row = row;
      this.showConfigDialog = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除普通用户信息编号为"' + userIds + '"的数据项？').then(function() {
        return delSmUser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/smUser/export', {
        ...this.queryParams
      }, `smUser_${new Date().getTime()}.xlsx`)
    },
    /** 搜索按钮操作 */
    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
    },
  }
};
</script>
