<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="companyUserType">
        <el-select v-model="queryParams.companyUserType" placeholder="请选择人员类型" clearable size="small">
          <el-option
            v-for="dict in companyUserTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入账号（手机号）"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="">
        <el-date-picker
          v-model="achievementTimeRange"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="业绩筛选开始日期"
          end-placeholder="业绩筛选结束日期">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="部门" prop="department">-->
<!--        <el-input-->
<!--          v-model="queryParams.department"-->
<!--          placeholder="请输入部门"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option :value="item.value" :label="item.name" v-for="(item,index) in statusOptions" :key="index" />
        </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="['mall:mallSalesman:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['mall:mallSalesman:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['mall:mallSalesman:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          :loading="exportLoading"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['mall:mallSalesman:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mallSalesmanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="人员类型" align="center" prop="companyUserType">
        <template slot-scope="scope">
          <dict-tag :options="companyUserTypeOptions" :value="scope.row.companyUserType"/>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" >
        <template slot-scope="scope">
          <el-image :src="scope.row.avatar" style="width: 80px" :preview-src-list="[scope.row.avatar]"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="账号（手机号）" align="center" prop="phone" width="120" />
<!--      <el-table-column label="部门" align="center" prop="department" />-->
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <div v-if="scope.row.status == 0">正常</div>
          <div v-if="scope.row.status == 1">冻结</div>
        </template>
      </el-table-column>
      <el-table-column label="总成交金额（元）" align="center" prop="allOrderPrice" />
      <el-table-column label="总客户数" align="center" prop="allMemberUserCount" />
      <el-table-column label="总订单数" align="center" prop="allOrderCount" />
      <el-table-column label="创建时间" align="center" prop="createAt" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="openResetPwd(scope.row.id)"
            v-hasPermi="['mall:mallSalesman:edit']"
          >重置密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:mallSalesman:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:mallSalesman:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="showQrCode(scope.row)"
            v-if="scope.row.companyUserType === 1"
          >查看二维码</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="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="人员类型">
          <el-radio-group v-model="form.companyUserType">
            <el-radio
              v-for="dict in companyUserTypeOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="账号（手机号）" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入账号（手机号）" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="form.id == null">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <treeselect v-model="form.department" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <imageUpload v-model="form.avatar" :limit="1"/>
        </el-form-item>
<!--        <el-form-item label="绑定用户" prop="userId">-->
<!--          <el-select v-model="form.userId" filterable placeholder="请选择" >-->
<!--            <el-option-->
<!--              v-for="(item,index) in userList"-->
<!--              :key="index"-->
<!--              :label="item.name+item.phone"-->
<!--              :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="item.value" v-for="(item,index) in statusOptions" :key="index">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="创建时间" prop="createAt"  v-if="form.id != null">-->
<!--          <el-input v-model="form.createAt" placeholder="请输入创建时间" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="更新时间" prop="updateAt"  v-if="form.id != null">-->
<!--          <el-input v-model="form.updateAt" placeholder="请输入更新时间" />-->
<!--        </el-form-item>-->
      </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>

    <!-- 重置密码 -->
    <el-dialog title="重置密码" :visible.sync="rePwdOpen" width="500px" append-to-body>
      <el-form ref="rePwdForm" :model="rePwdForm" :rules="rePwdRules" label-width="80px">
<!--        <el-form-item label="原密码" prop="oldPassword">-->
<!--          <el-input type="password" :showPassword="true" v-model="rePwdForm.oldPassword" placeholder="请输入原密码" />-->
<!--        </el-form-item>-->
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" :showPassword="true" v-model="rePwdForm.newPassword" placeholder="请输入新密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResetPassword">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码 -->
    <el-dialog title="二维码" :visible.sync="codeOpen" width="500px" append-to-body>
      <el-image
        style="width: 100px; height: 100px"
        :src="qrCode"
        :preview-src-list="[qrCode]">
      </el-image>
    </el-dialog>
  </div>
</template>

<script>
import {
  resetPassword,
  listMallSalesman,
  getMallSalesman,
  delMallSalesman,
  addMallSalesman,
  updateMallSalesman,
  exportMallSalesman,
  selectList,
  selectMemberList,
  getSalesmanQrCode
} from "@/api/mall/mallSalesman";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "MallSalesman",
  components: { Treeselect },
  props: ["companyId"],
  data() {
    return {
      // 公司人员类型：0-公司管理员，1-业务员字典
      companyUserTypeOptions: [],
      userList:[],
      statusOptions:[
        {name:'正常',value:0},
        {name:'冻结',value:1}
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业务员表格数据
      mallSalesmanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 业绩时间范围
      achievementTimeRange:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        phone: null,
        password: null,
        name: null,
        department: null,
        avatar: null,
        status: null,
        createAt: null,
        updateAt: null,
        delFlag: null,
        companyId: null,
        sysUserId: null,
        roleId: null,
        companyUserType: null,
        params:{
          beginAchievementTime:'',
          endAchievementTime:''
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: "账号（手机号）不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的账号（手机号）",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        department: [
          { required: true, message: "部门不能为空", trigger: "blur" }
        ],
        // userId: [
        //   { required: true, message: "绑定用户不能为空", trigger: "blur" }
        // ],
      },
      // 部门树选项
      deptOptions: undefined,
      rePwdForm:{},
      rePwdOpen:false,
      // 表单校验
      rePwdRules: {
        oldPassword: [
          { required: true, message: "原密码不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '密码长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '新密码长度必须介于 2 和 20 之间', trigger: 'blur' }
        ]
      },
      qrCode: null,
      codeOpen: false,
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("company_user_type").then(response => {
      this.companyUserTypeOptions = response.data;
    });
    // console.log(this.form.id != null)
  },
  methods: {
    /** 查询用户列表 */
    getSelectMemberList() {
      selectMemberList().then(res =>{
        this.userList = res.data
      })
    },

    /** 打开重置密码弹框 */
    openResetPwd(salesmanId){
      this.reset();
      this.rePwdForm.salesmanId = salesmanId
      this.rePwdOpen = open;
    },
    /** 重置密码提交 */
    submitResetPassword(){
      this.$refs["rePwdForm"].validate(valid => {
        if (valid) {
          resetPassword(this.rePwdForm).then(res => {
            this.msgSuccess("修改成功");
            this.rePwdOpen = false;
            this.reset()
          })
        }
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询业务员列表 */
    getList() {
      this.loading = true;
      if (this.companyId != null){
        this.queryParams.companyId = this.companyId;
      }
      if (null != this.achievementTimeRange && '' != this.achievementTimeRange) {
        this.queryParams.params["beginAchievementTime"] = this.achievementTimeRange[0];
        this.queryParams.params["endAchievementTime"] = this.achievementTimeRange[1];
      }
      listMallSalesman(this.queryParams).then(response => {
        this.mallSalesmanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.rePwdOpen = false
      this.reset();
    },
    // 表单重置
    reset() {
      // this.form = {
      //   id: '',
      //   phone: '',
      //   password: '',
      //   name: '',
      //   department: undefined,
      //   avatar: '',
      //   status: 0,
      //   createAt: '',
      //   updateAt: '',
      //   delFlag: ''
      // };
      this.form = {
        id: null,
        phone: null,
        password: null,
        name: null,
        department: null,
        avatar: null,
        status: 0,
        createAt: null,
        updateAt: null,
        delFlag: null,
        companyId: null,
        sysUserId: null,
        roleId: null,
        companyUserType: 1,
      }
      this.rePwdForm = {
        salesmanId: '',
        oldPassword: '',
        newPassword: ''
      };
      // this.resetForm("form");
      this.resetForm("rePwdForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.achievementTimeRange = []
      this.queryParams.params["beginAchievementTime"] = ''
      this.queryParams.params["endAchievementTime"] = ''
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.getSelectMemberList()
      this.open = true;
      this.title = "添加人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // this.getSelectMemberList()
      const id = row.id || this.ids
      getMallSalesman(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业务员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.companyId = this.companyId;
        if (valid) {
          if (this.form.id != null) {
            updateMallSalesman(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMallSalesman(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除业务员编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMallSalesman(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有业务员数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallSalesman(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    showQrCode(row){
      this.qrCode = null;
      let data = {
        id: row.id
      }
      getSalesmanQrCode(data).then(res =>{
        this.qrCode = res.data.qrCode;
        this.codeOpen = true;
      })
    },
  }
};
</script>
