<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="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户类型" prop="isMch">
        <el-select v-model="queryParams.isMch" placeholder="请选择用户类型" clearable @change="handleQuery">
          <el-option label="商户" :value="true"/>
          <el-option label="普通用户" :value="false"/>
        </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>
        <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"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'isMch'">
              <el-tag :type="d.row.isMch ? 'primary' : 'success'" >{{d.row.isMch ? '商户' : '普通用户'}}</el-tag>
            </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 === 'storeCount'">
              {{d.row.storeCount | defaultValue}} 间
            </template>
            <template v-else-if="column.key === 'rechargeAmount'">
              {{d.row.rechargeAmount | 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 === 'serviceRate'">
              <template v-if="d.row.serviceRate == null || d.row.serviceType == null">跟随渠道</template>
              <template v-else>
                <dict-tag :options="dict.type.service_type" :value="d.row.serviceType"/>
                {{d.row.serviceRate}} {{serviceUnit(d.row.serviceType)}}
              </template>
            </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 === '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
            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-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>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改普通用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col :span="span" label="用户头像" prop="avatar">
            <image-upload v-model="form.avatar" :limit="1"/>
          </form-col>
          <form-col :span="span" label="用户类型" prop="isMch">
            <el-select v-model="form.isMch" placeholder="请选择用户类型" style="width: 100%">
              <el-option label="商户" :value="true"/>
              <el-option label="普通用户" :value="false"/>
            </el-select>
          </form-col>
          <form-col :span="span" label="用户名称" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名称" :maxlength="20" ></el-input>
          </form-col>
          <form-col :span="span" label="用户昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入用户昵称" :maxlength="20" ></el-input>
          </form-col>
          <form-col :span="span" label="手机号" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号" :maxlength="11" show-word-limit
                      clearable prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
          </form-col>
          <form-col :span="span * 2" label="设备服务费" prop="serviceRate"  label-width="7em">
            <el-input v-model="form.serviceRate" placeholder="请输入设备服务费" type="number">
              <template #prepend>
                <el-select v-model="form.serviceType" placeholder="请选择设备服务费收取方式" style="width: 10em">
                  <el-option
                    v-for="dict in dict.type.service_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
              <template #append>{{serviceUnit(form.serviceType)}}</template>
            </el-input>
          </form-col>
          <form-col :span="span * 2" label="提现服务费" prop="withdrawServiceRate" label-width="7em">
            <el-input v-model="form.withdrawServiceRate" placeholder="请输入提现服务费" type="number">
              <template #prepend>
                <el-select v-model="form.withdrawServiceType" placeholder="请选择提现服务费收取方式" style="width: 10em">
                  <el-option
                    v-for="dict in dict.type.withdraw_service_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
              <template #append>{{withdrawServiceUnit(form.withdrawServiceType)}}</template>
            </el-input>
          </form-col>
          <form-col :span="span * 2" label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" :maxlength="500" show-word-limit type="textarea"/>
          </form-col>
          <form-col :span="span" label="是否设备管理员" prop="deviceAdmin" label-width="9em">
            <el-switch v-model="form.deviceAdmin" active-text="是" inactive-text="否" @change="onChangeDeviceAdmin"/>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSmUser,
  getSmUser,
  addSmUser,
  updateSmUser,
  delSmUser,
  updateServiceRate,
  resetSmUserService
} from '@/api/system/smUser'
import { $serviceType, $showColumns, $withdrawServiceType } from '@/utils/mixins'
import UserLink from '@/components/Business/SmUser/UserLink.vue'

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

export default {
  name: "SmUser",
  mixins: [$showColumns, $serviceType, $withdrawServiceType],
  components: { UserLink },
  dicts: ['sm_user_status', 'user_type', 'sys_user_sex', 'service_type', 'withdraw_service_type'],
  computed: {
    serviceUnit() {
      return (type) => {
        return type === '2' ? '元' : '%';
      }
    }
  },
  data() {
    return {
      defaultSort,
      span: 12,
      columns: [
        {key: 'userId', visible: true, label: '用户ID', align: 'center', minWidth: "80", sortable: true},
        {key: 'phonenumber', visible: true, label: '手机号码', align: 'center', minWidth: null, sortable: true},
        {key: 'userName', visible: false, label: '用户名称', align: 'center', minWidth: null, sortable: false},
        {key: 'isMch', visible: true, label: '用户类型', align: 'center', minWidth: null, sortable: true},
        {key: 'remark', visible: true, label: '备注', align: 'center', minWidth: null, sortable: false, overflow: true},
        {key: 'status', visible: true, label: '账号状态', align: 'center', minWidth: null, sortable: true},
        {key: 'createTime', visible: true, label: '创建时间', align: 'center', minWidth: "120", sortable: true},
        {key: 'rechargeAmount', visible: true, label: '充值金额', align: 'center', minWidth: null, sortable: true},
        {key: 'withDrawlAmount', visible: true, label: '提现金额', align: 'center', minWidth: null, sortable: true},
        {key: 'balance', visible: true, label: '账户余额', align: 'center', minWidth: null, sortable: true},
        {key: 'serviceRate', visible: true, label: '设备服务费', align: 'center', minWidth: null, sortable: true},
        {key: 'withdrawServiceRate', visible: true, label: '提现服务费', align: 'center', minWidth: null, sortable: true},
        {key: 'storeCount', visible: true, label: '店铺数量', align: 'center', minWidth: null, sortable: false},
        {key: 'deviceCount', visible: true, label: '设备数量', align: 'center', minWidth: null, sortable: false},
        {key: 'deviceAdmin', visible: false, label: '设备管理员', align: 'center', minWidth: null, sortable: false},
      ],
      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,
        isMch: null,
        phonenumber: null,
        serviceType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [{
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '请选择性别',
          trigger: 'change'
        }],
        identityCard: [{
          pattern: /^(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
          message: '请输入正确的身份证',
          trigger: 'change'
        }],
        phonenumber: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        address: [],
      },
    };
  },
  created() {
    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();
        })
      })
    },
    onChangeDeviceAdmin(val) {
      if (val) {
        this.$confirm('【高危操作】是否确认设置用户为设备管理员？<br/>用户将可以通过微信小程序注册设备！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          this.form.deviceAdmin = true;
        }).catch((e) => {
          this.form.deviceAdmin = false;
        });
      }
    },
    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;
      });
    },
    // 取消按钮
    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'
      };
      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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 查看按钮操作 */
    handleSee(row) {
      this.$router.push({path: '/mch/detail', query: {userId: row.userId}})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getSmUser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateSmUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSmUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    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`)
    }
  }
};
</script>
