<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="realOrUserName">
        <el-input
          v-model="queryParams.realOrUserName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <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="referenceName">
        <el-input
          v-model="queryParams.referenceName"
          placeholder="请输入推广人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="`直属${FieldName.AGENT}`" prop="agentName" :label-width="`${FieldName.AGENT.length + 3}em`">
        <el-input
          v-model="queryParams.agentName"
          :placeholder="`请输入直属${FieldName.AGENT}名称`"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后登录IP" prop="loginIp" label-width="6em">
        <el-input
          v-model="queryParams.loginIp"
          placeholder="请输入最后登录IP"
          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">
      <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 :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="column.key === 'investorCount'">
              {{d.row.investorCount | defaultValue}} 人
            </template>
            <template v-else-if="['totalIncome', 'withDrawlAmount', 'balance', 'billAmount'].includes(column.key)">
              {{d.row[column.key] | money | defaultValue}} 元
            </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 === '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)"
            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="头像">
            <image-upload v-model="form.avatar" :limit="1"/>
          </form-col>
          <form-col :span="span" label="用户类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择用户类型" style="width: 100%"  :disabled="oldUserType !== SmUserType.NORMAL">
              <el-option
                v-for="dict in dict.type.user_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </form-col>
          <form-col :span="span" label="运营商" prop="deptId" v-if="deptId === ROOT_DEPT">
            <dept-tree-select v-model="form.deptId" @change="onChangeDept" :disabled="isEdit"/>
          </form-col>
          <form-col :span="span" label="推广人" prop="referenceId" v-if="![SmUserType.NORMAL, SmUserType.BUSINESS_PLACE].includes(form.type)">
            <user-input v-model="form.referenceId" @change="onChangeReference" show-type :query="referenceQuery" :before-open="beforeOpenReference"/>
          </form-col>
          <form-col :span="span" label="用户名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名" />
          </form-col>
          <form-col :span="span" label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" :maxlength="11" show-word-limit/>
          </form-col>
          <form-col :span="span" label="密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入密码，为空则不修改" type="password" :maxlength="32" show-word-limit/>
          </form-col>
          <form-col :span="span" label="分成比例" prop="point" v-if="![SmUserType.NORMAL, SmUserType.BUSINESS_PLACE].includes(form.type)">
            <el-input-number v-model="form.point" placeholder="请输入分成比例" :precision="2" controls-position="right" :min="0" style="width: calc(100% - 1.5em)"/> %
          </form-col>
          <form-col :span="span * 2" label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </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, listAgent, listBiz, listInvestor, listStoreUser
} from '@/api/system/smUser'
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, ROOT_DEPT, SmUserType } from '@/utils/constants'
import { mapGetters } from 'vuex'

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

export default {
  name: "SmUser",
  mixins: [$showColumns, $serviceType, $withdrawServiceType],
  dicts: ['sm_user_status', '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() {
      return SmUserType
    },
    // 推广人查询条件
    referenceQuery() {
      let query = {
        excludeId: this.form.userId,
        deptId: this.form.deptId,
      }
      if (this.type === SmUserType.AGENT) {
        query.type = SmUserType.AGENT;
      }
      if (this.type === SmUserType.BIZ) {
        query.types =  [SmUserType.AGENT, SmUserType.BIZ]
      }
      if (this.type === SmUserType.INVESTOR) {
        query.types = [SmUserType.BIZ]
      }
      return query;
    },
    rules() {
      return {
        userName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
        phonenumber: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1(3|4|5|7|8|9)\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
        ],
        referenceId: [
          {required: this.form.type !== SmUserType.AGENT, message: '请选择推广人', trigger: 'blur' }
        ],
        deptId: [
          {required: true,message: '请选择运营商', trigger: 'blur' }
        ],
        point: [
          { required: true, type: 'number', message: "分成比例不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'blur' }
        ]
      }
    }
  },
  data() {
    return {
      ROOT_DEPT,
      // 旧的用户类型
      oldUserType: null,
      defaultSort,
      type: null, // 用户类型
      span: 12,
      columns: [
        {key: 'userId', visible: false, label: '用户ID', align: 'center', minWidth: "80", sortable: true, width: null},
        {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: 'agentId', visible: true, label: `直属${FieldName.AGENT}`, align: 'center', minWidth: null, sortable: false, 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: 'totalIncome', visible: true, label: '收入金额', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'withDrawlAmount', visible: true, label: '提现金额', align: 'center', minWidth: null, sortable: true, width: null},
        {key: 'balance', 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: 'investorCount', visible: false, label: `${FieldName.INVESTOR}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'storeCount', visible: false, label: `${FieldName.STORE}数`, align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deviceCount', visible: false, label: '设备数', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'billCount', visible: false, label: '订单数', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'billAmount', visible: false, label: '订单总额', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deptName', visible: false, label: '运营商', align: 'center', minWidth: null, sortable: false, width: null},
        {key: 'deviceAdmin', visible: false, 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,
        isMch: null,
        phonenumber: null,
        serviceType: null,
        status: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    if (this.query.type) {
      this.type = this.query.type;
    }
    if (this.$route.query.type) {
      this.type = this.$route.query.type;
    }

    this.queryParams.type = this.type;
    if (this.type === SmUserType.AGENT) {
      this.hideColumn(['agentId'])
    } else if (this.type === SmUserType.INVESTOR) {
      this.hideColumn(['investorCount', 'billAmount']);
    } else if (this.type === SmUserType.BUSINESS_PLACE) {
      this.hideColumn(['investorCount', 'billAmount', 'point', 'agentId', 'deviceCount', 'billCount', 'billAmount', 'referenceId'])
    } else if (this.type === SmUserType.NORMAL) {
      this.hideColumn(['investorCount', 'billAmount', 'point', 'agentId', 'deviceCount', 'billCount', 'billAmount', 'storeCount', 'referenceId', 'totalIncome', 'withDrawlAmount'])
    }

    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }

    this.getList();
  },
  methods: {
    onChangeDept(dept) {
      if (this.form.referenceId != null) {
        this.form.referenceId = null;
        this.$message.info("更换运营商，请重新选择推广人")
      }
    },
    beforeOpenReference() {
      if (this.form.deptId == null) {
        this.$message.warning("请先选择运营商");
        return false;
      }
      return true;
    },
    onChangeReference(user) {
      this.form.deptId = user.deptId;
    },
    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;
      if (this.type === SmUserType.AGENT) {
        listAgent(this.queryParams).then(res => {
          this.afterList(res);
        })
      } else if (this.type === SmUserType.BIZ) {
        listBiz(this.queryParams).then(res => {
          this.afterList(res);
        })
      } else if (this.type === SmUserType.INVESTOR) {
        listInvestor(this.queryParams).then(res => {
          this.afterList(res);
        })
      } else if (this.type === SmUserType.BUSINESS_PLACE) {
        listStoreUser(this.queryParams).then(res => {
          this.afterList(res);
        })
      } else {
        listSmUser(this.queryParams).then(res => {
          this.afterList(res);
        });
      }
    },
    afterList(res) {
      this.smUserList = res.rows;
      this.total = res.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',
        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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.oldUserType = null;
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 查看按钮操作 */
    handleSee(row) {
      this.$router.push({path: `/smUser/user/${row.userId}`})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids
      getSmUser(userId).then(response => {
        this.form = response.data;
        this.oldUserType = this.form.type;
        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>
