package com.cftech.base.org.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.api.QyTagUtil;
import com.cftech.base.org.api.QyUserUtil;
import com.cftech.base.org.model.OrgUnit;
import com.cftech.base.org.model.Position;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.model.vo.QyuserVO;
import com.cftech.base.org.service.OrgUnitService;
import com.cftech.base.org.service.PositionService;
import com.cftech.base.org.service.QyuserService;
import com.cftech.base.org.service.TerminalUserService;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.CondType;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Cond;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.Encrypt;
import com.cftech.core.util.SystemConfig;
import com.cftech.shop.qrcode.model.WxQrcode;
import com.cftech.shop.qrcode.service.WxQrcodeService;
import com.cftech.sys.model.User;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import com.cftech.sys.service.UserService;
import javafx.scene.shape.QuadCurve;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 权限字符串说明:
 * 查看:public static final String QYUSER_VIEW = "qy:qyuser:view"
 * 查看:public static final String QYUSER_EDIT = "qy:qyuser:edit"
 * qyuserWeb
 * Created by Neil 14/02/2017.
 */
@Slf4j
@Controller
@RequestMapping("/a/qyuser")
public class QyuserController {

    /**
     * qyuserService
     */
    @Autowired
    private QyuserService qyuserService;
    @Autowired
    private OrgUnitService orgUnitService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private QyUserUtil qyUserUtil;
    @Autowired
    private WxQrcodeService wxQrcodeService;
    @Autowired
    private UserService userService;

    private final static String qyAccounts = SystemConfig.p.getProperty("AIDEA_QY_ACCOUNTS");

    //返回列表页面
    @RequiresPermissions(value = PermissionSign.QYUSER_VIEW)
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String qyuserList(HttpServletRequest request, Model model) {
        Long accountId = Long.parseLong(qyAccounts);
        model.addAttribute("accountId", accountId);
        return "managerqyuser/qyuserlist";
    }

    //返回编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.QYUSER_VIEW)
    @RequestMapping(value = "/form", method = {RequestMethod.GET, RequestMethod.POST})
    public String form(HttpServletRequest request, String id, Model model , String orgId) {
        Long accountId = Long.parseLong(qyAccounts);
        if (!StringUtils.isEmpty(id)) {
            Qyuser qyuser = qyuserService.fetchById(id);
            if (qyuser.getOrgId() != null) {
                OrgUnit orgUnit = orgUnitService.fetchById(qyuser.getOrgId());
                model.addAttribute("orgName", orgUnit.getOrgName());
            }
            if (qyuser.getPositionId() != null) {
                Position position = positionService.fetchById(qyuser.getPositionId());
                model.addAttribute("positionName", position.getName());
            }

            model.addAttribute("data", qyuser);
            model.addAttribute("accountId", qyuser.getAccountsId());
        } else {
            if (!StringUtils.isEmpty(orgId)){
                Qyuser qyuser = new Qyuser();
                qyuser.setOrgId(Long.valueOf(orgId));
                OrgUnit orgUnit = orgUnitService.fetchById(orgId);
                model.addAttribute("orgName", orgUnit.getOrgName());
                model.addAttribute("data", qyuser);
            }
            model.addAttribute("accountId", accountId);
        }
        return "managerqyuser/qyuseradd";
    }

    //提交编辑页面（新增、修改）
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/formData", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject qyuserListformData(Qyuser qyuser, Model model, HttpServletRequest request, String passwordQyUser, String loginNameQyUser) {
        Long accountId = Long.parseLong(qyAccounts);
        JSONObject rtnJson = new JSONObject();
        Long userId = UserUtils.getUser().getId();
        Conds userConds = new Conds();
        userConds.equal("t.userid", qyuser.getId());
        User user = userService.fetchSearchByConds(userConds);

        try {
            if (qyuser != null && qyuser.getId() != null) {
                Conds conds = new Conds();
                conds.equal("t.username", loginNameQyUser);
                conds.equal("t.delflag", 0);
                conds.equal("t.state", 0);
                conds.notEqual("t.id", user.getId());
                User userExits = userService.fetchSearchByConds(conds);
                if (userExits != null) {
                    //登录账号重复
                    rtnJson.put("errorNo", 3);
                    return rtnJson;
                }
                qyuser.setUpdateBy(userId);
                qyuser.setWxuserId(loginNameQyUser);
                qyUserUtil.updateQyUser(qyuser);
                if (!StringUtils.isEmpty(qyuser.getImg())) {
                    String domainName = SystemConfig.p.getProperty("QY_DOMAIN");
                    qyuser.setDescription(domainName + qyuser.getImg());
                }
                qyuserService.update(qyuser);
                if (!StringUtils.isEmpty(loginNameQyUser)) {
                    user.setUsername(loginNameQyUser);
                }
                if (!StringUtils.isEmpty(passwordQyUser)) {
                    user.setPassword(passwordQyUser);
                }
                userService.update(user);
                rtnJson.put("errorNo", 0);
            } else {
                Conds conds = new Conds();
                conds.equal("t.username", loginNameQyUser);
                conds.equal("t.delflag", 0);
                conds.equal("t.state", 0);
                User userExits = userService.fetchSearchByConds(conds);
                if (userExits != null) {
                    //登录账号重复
                    rtnJson.put("errorNo", 3);
                    return rtnJson;
                }

                user = new User();
                //新增
                qyuser.setPeakVal(0L);
                qyuser.setAssigned(0L);
                qyuser.setUnAssigned(0L);
                qyuser.setDelFlag(false);
                qyuser.setAccountsId(accountId);
                qyuser.setCreateBy(UserUtils.getUser().getId());
                qyuser.setUpdateBy(UserUtils.getUser().getId());
                qyuser.setWxuserId(loginNameQyUser);
                //同步至企业微信
                qyUserUtil.updateQyUser(qyuser);
                user.setPassword(passwordQyUser);
                user.setUsername(loginNameQyUser);
                user.setState("0");
                if (!StringUtils.isEmpty(qyuser.getImg())) {
                    String domainName = SystemConfig.p.getProperty("QY_DOMAIN");
                    qyuser.setDescription(domainName + qyuser.getImg());
                }
                qyuserService.save(qyuser);
                user.setUserid(qyuser.getId());
                user.setDefaultAccId(UserUtils.getmpaccounts(request));
                userService.save(user);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = PermissionSign.QYUSER_VIEW)
    @RequestMapping(value = "/listData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Qyuser qyuser, HttpServletRequest request) {
        Long accountId = Long.parseLong(qyAccounts);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(qyuser.getName())) {
            conds.like("t.name", qyuser.getName());
        }
        if (!StringUtils.isEmpty(qyuser.getMobile())) {
            conds.like("t.mobile", qyuser.getMobile());
        }
        if (!StringUtils.isEmpty(qyuser.getRole())) {
            conds.equal("t.role", qyuser.getRole());
        }
        if (!StringUtils.isEmpty(qyuser.getDescription())) {
            conds.like("t.description", qyuser.getDescription());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);
        Long orgId = null;
//        if (qyuser.getOrgId() != null) {
//            orgId = qyuser.getOrgId();
//        } else {
//            User user = UserUtils.getUser();
//            Qyuser currentQyyuser = qyuserService.fetchById(user.getUserid());
//            orgId = currentQyyuser.getOrgId();
//        }

        List<QyuserVO> list = qyuserService.fetchSearchVOByPage(orgId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("t.del_flag", Constants.DEL_FLAG_0);
        myCond.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(qyuser.getName())) {
            myCond.like("t.name", qyuser.getName());
        }
        if (!StringUtils.isEmpty(qyuser.getMobile())) {
            myCond.like("t.mobile", qyuser.getMobile());
        }
        Integer counts = qyuserService.count(orgId, myCond);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    /**
     * 解绑绑定导购和二维码的功能
     *
     * @param userId
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/unBindQrcode", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject unBindQrcode(HttpServletRequest request, Long userId, String type) {
        JSONObject retObj = new JSONObject();
        Qyuser qyuser = qyuserService.fetchById(userId);
        if (com.cftech.core.util.StringUtils.isNotBlank(qyuser.getQrcode())) {
            //如果原来有数据，需要先取消绑定原有的记录
            Long accountId = Long.parseLong(qyAccounts);
            Conds conds = new Conds();
            conds.equal("t.del_flag", Constants.DEL_FLAG_0);
            conds.equal("t.accounts_id", UserUtils.getmpaccounts(request));
            conds.equal("t.type", type);
            conds.equal("t.bind_id", userId);

            List<WxQrcode> list = wxQrcodeService.fetchSearchByPage(0L, conds, null, 0, 0);
            if (list != null && list.size() > 0) {
                WxQrcode oldQrcode = list.get(0);
                oldQrcode.setBindId(null);
                wxQrcodeService.updateBindId(oldQrcode);
                retObj.put("errorNo", "0");
            } else {
                retObj.put("errorNo", "1");
                retObj.put("errorMsg", "没有找到绑定的二维码");
            }
        } else {
            retObj.put("errorNo", "2");
            retObj.put("errorMsg", "并未绑定过二维码");
        }

        //做2方的更新操作
        Qyuser newUser = new Qyuser();
        newUser.setId(userId);
        newUser.setQrcode("");

        qyuserService.update(newUser);

        retObj.put("errorNo", "0");

        return retObj;
    }


    //删除数据
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(HttpServletRequest request, String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            Qyuser qyuser = qyuserService.fetchById(id);
//            if (!qyUserUtil.delete(qyuser)) {
//                log.error("user delete 同步微信端失败，{}", qyuser.toString());
//            }
            if (com.cftech.core.util.StringUtils.isNotBlank(qyuser.getQrcode())) {
                //如果原来有数据，需要先取消绑定原有的记录
                Long accountId = Long.parseLong(qyAccounts);
                Conds conds = new Conds();
                conds.equal("t.del_flag", Constants.DEL_FLAG_0);
                conds.equal("t.accounts_id", accountId);
                conds.equal("t.type", "1");
                conds.equal("t.bind_id", id);

                List<WxQrcode> list = wxQrcodeService.fetchSearchByPage(0L, conds, null, 0, 0);
                if (list != null && list.size() > 0) {
                    WxQrcode oldQrcode = list.get(0);
                    oldQrcode.setBindId(null);
                    wxQrcodeService.updateBindId(oldQrcode);
                }
            }
            Conds conds = new Conds();
            conds.equal("userid", id);
            User user = userService.fetchSearchByConds(conds);
            if (user != null) {
                user.setDelflag(1);
                userService.update(user);
            }
            qyuserService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    @RequestMapping(value = "/exportExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYUSER_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response, Qyuser qyuser) {
        Long accountId = Long.parseLong(qyAccounts);
        Sort sort = new Sort("t.create_time", OrderType.DESC);
        Conds conds = new Conds();
        conds.equal("t.del_flag", 0);
        conds.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(qyuser.getName())) {
            conds.like("t.name", qyuser.getName());
        }
        if (!StringUtils.isEmpty(qyuser.getMobile())) {
            conds.like("t.mobile", qyuser.getMobile());
        }
        if (!StringUtils.isEmpty(qyuser.getRole())) {
            conds.equal("t.role", qyuser.getRole());
        }
        if (!StringUtils.isEmpty(qyuser.getDescription())) {
            conds.like("t.description", qyuser.getDescription());
        }
//        User user = UserUtils.getUser();
//        Qyuser currentQyyuser = qyuserService.fetchById(user.getUserid());
//        Long orgId = currentQyyuser.getOrgId();
        List<QyuserVO> qyusers = qyuserService.fetchSearchVOByPage(null, conds, sort, 0, 0);
        qyusers.stream().forEach(o -> {
            String position = o.getUserType();
            switch (position) {
                case "0":
                    o.setUserType("其他");
                    break;
                case "1":
                    o.setUserType("药师");
                    break;
                case "2":
                    o.setUserType("客服");
                    break;
                case "3":
                    o.setUserType("医生");
                    break;
                case "4":
                    o.setUserType("订单员");
                    break;
            }
        });

        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(QyuserVO.class, response).toExcel(qyusers, "企业人员信息");
    }

    @RequestMapping(value = "/templateExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    public void templateExcel(HttpServletRequest request, HttpServletResponse response) {
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(QyuserVO.class, response).toExcel(null, "企业人员信息");
    }

    @RequestMapping(value = "/importExcel", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    public String importExcel(HttpServletRequest request, MultipartFile file, Model model) {
        Long accountId = Long.parseLong(qyAccounts);
        StringBuffer stringBuffer = new StringBuffer();
        if (file == null) {
            return qyuserList(request, model);
        }
        // 构造临时路径来存储上传的文件
        String uploadPath = System.getProperty("java.io.tmpdir");
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String fileName = file.getOriginalFilename();
        String filePath = uploadPath + File.separator + fileName;
        File storeFile = new File(filePath);
        try {
            file.transferTo(storeFile);
            ExcelKit.$Import().setEmptyCellValue(null).readExcel(storeFile, rowData -> {
                //2是姓名
                if (!StringUtils.isEmpty(rowData.get(4))) {
                    Qyuser qyuser = new Qyuser();
                    qyuser.setAccountsId(accountId);
                    Conds isConds = new Conds();
                    isConds.equal("t.mobile", rowData.get(1));
                    isConds.equal("u.username", rowData.get(4));
                    isConds.equal("u.delflag", 0);
                    isConds.equal("u.state", 0);
                    Qyuser qyuserExits = qyuserService.fetchSearchByConds(isConds);
                    if (qyuserExits != null) {
                        stringBuffer.append("重复导入，" + rowData.toString() + "<br/>");
                        log.info("导入SA人员时出现重复账号,重复账号的行数据是:" + rowData.toString());
                        return;
                    }

                    qyuser.setName(rowData.get(0));
                    qyuser.setEmail(rowData.get(2));
                    qyuser.setMobile(rowData.get(1));
                    qyuser.setWxuserId(rowData.get(4));
                    qyuser.setUserType(rowData.get(5));
                    qyuser.setGender(rowData.get(6));

                    if (!StringUtils.isEmpty(rowData.get(3).toString())) {
                        OrgUnit orgUnit = orgUnitService.findByAccountIdAndNumber(accountId, rowData.get(3).toString());
                        qyuser.setOrgId(orgUnit.getId());
                    } else {
                        stringBuffer.append("组织导入为空，" + rowData.toString() + "<br/>");
                        log.info("导入SA人员时出现重复账号,重复账号的行数据是:" + rowData.toString());
                        return;
                    }


                    //qyuser.setDescription(rowData.get(3));
                    qyUserUtil.updateQyUser(qyuser);
                    qyuserService.save(qyuser);
                    User user = new User();
                    user.setState("0");
                    user.setUsername(rowData.get(4));
                    user.setPassword(Encrypt.SHA256(rowData.get(4)));
                    user.setDelflag(0);
                    user.setUserid(qyuser.getId());
                    userService.save(user);
                } else {
                    log.info("账号为空," + rowData.toString() + "<br/>");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        model.addAttribute("accountId", accountId);
        model.addAttribute("text", stringBuffer.toString());
        return "managerqyuser/qyuserlist";
    }


    @RequiresPermissions(value = PermissionSign.QYUSER_VIEW)
    @RequestMapping(value = "/listDataNoAuth", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public JSONObject listDataNoAuth(int iDisplayStart, int iDisplayLength, Qyuser qyuser, HttpServletRequest request) {
        Long accountId = Long.parseLong(qyAccounts);
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(qyuser.getName())) {
            conds.like("t.name", qyuser.getName());
        }
        if (!StringUtils.isEmpty(qyuser.getMobile())) {
            conds.like("t.mobile", qyuser.getMobile());
        }
        if (!StringUtils.isEmpty(qyuser.getDescription())) {
            conds.like("t.description", qyuser.getDescription());
        }
        Sort sort = new Sort("t.create_time", OrderType.DESC);
        Long orgId = null;
        if (qyuser.getOrgId() != null) {
            orgId = qyuser.getOrgId();
        } else {
//            User user = UserUtils.getUser();
//            Qyuser currentQyyuser = qyuserService.fetchById(user.getUserid());
            orgId = 0L;//currentQyyuser.getOrgId();
        }

        List<QyuserVO> list = qyuserService.fetchSearchVOByPage(orgId, conds, sort, iDisplayStart, iDisplayLength);

        Conds myCond = new Conds();
        myCond.equal("t.del_flag", Constants.DEL_FLAG_0);
        myCond.equal("t.accounts_id", accountId);
        if (!StringUtils.isEmpty(qyuser.getName())) {
            myCond.like("t.name", qyuser.getName());
        }
        if (!StringUtils.isEmpty(qyuser.getMobile())) {
            myCond.like("t.mobile", qyuser.getMobile());
        }
        Integer counts = qyuserService.count(orgId, myCond);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    @RequestMapping(value = "/sync", method = {RequestMethod.GET, RequestMethod.POST})
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @ResponseBody
    public JSONObject sync(HttpServletRequest request, Model model) {
        Long accountId = Long.parseLong(qyAccounts);
        // 同步微信端的人员，下拉到本地为主
        JSONObject retObj = qyUserUtil.sync(accountId);
        log.info("同步结果: {}", retObj.toJSONString());
        return retObj;
    }


    /**
     * 绑定门店店长
     *
     * @param request
     * @param storeId   门店Id
     * @param managerId 店长Id
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/bindManger", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject bindManger(HttpServletRequest request, Long storeId, Long managerId) {
        JSONObject retObj = new JSONObject();

        Qyuser qyuser = qyuserService.fetchById(managerId);
//

//        Store store = new Store();
//        store.setId(storeId);
//        store.setManagerId(managerId);
//        store.setManagerName(qyuser.getName());
//
//        storeService.update(store);

        //更新人员信息
        Qyuser newQyuser = new Qyuser();
        newQyuser.setId(managerId);
        newQyuser.setStoreId(storeId);
        newQyuser.setRole("1");
        qyuserService.update(newQyuser);

        retObj.put("errorNo", "0");

        return retObj;
    }

//    /**
//     * 绑定门店店长
//     * @param request
//     * @param storeId  门店Id
//     * @param employeeIds 雇员Id数组
//     * @return
//     */
//    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
//    @RequestMapping("/bindEmployee")
//    @ResponseBody
//    public JSONObject bindEmployee(HttpServletRequest request,Long storeId, Long[] employeeIds) {
//        JSONObject retObj = new JSONObject();
//
//        Store tarStore = storeService.fetchById(storeId);
//
//        for (int i = 0, j = employeeIds.length; i < j; i++) {
//            //更新人员信息
//            Qyuser newQyuser = new Qyuser();
//            newQyuser.setId(employeeIds[i]);
//            newQyuser.setStoreId(storeId);
//            newQyuser.setStoreName(tarStore.getName());
//            newQyuser.setRole("2");
//            qyuserService.update(newQyuser);
//        }
//
//
//        retObj.put("errorNo", "0");
//
//        return retObj;
//    }

    /**
     * 绑定门店店长
     *
     * @param id 人员Id
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/unBindStore", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject unBindStore(Long id) {
        JSONObject retObj = new JSONObject();
        //更新人员信息
        qyuserService.updateStoreInfo(id, "0", null, null);

        retObj.put("errorNo", "0");

        return retObj;
    }

    /**
     * 绑定门店店长
     *
     * @param employeeIds 人员Ids
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/unBindEmployee", method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject unBindEmployee(Long[] employeeIds) {
        JSONObject retObj = new JSONObject();
        for (int i = 0, j = employeeIds.length; i < j; i++) {
            //更新人员信息
            qyuserService.updateStoreInfo(employeeIds[i], "0", null, null);
        }
        retObj.put("errorNo", "0");

        return retObj;
    }


    /**
     * 绑定人员和二维码的功能
     *
     * @param id
     * @param wxQrcodeId
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/bindQrcode", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject bindQrcode(HttpServletRequest request, Long id, Long wxQrcodeId) {
        JSONObject retObj = new JSONObject();
        Qyuser qyuser = qyuserService.fetchById(id);
        if (!StringUtils.isEmpty(qyuser.getQrcode())) {
            //如果原来有数据，需要先取消绑定原有的记录
            Long accountId = Long.parseLong(qyAccounts);
            Conds conds = new Conds();
            conds.equal("t.del_flag", Constants.DEL_FLAG_0);
            conds.equal("t.accounts_id", accountId);
            conds.equal("t.type", "1");
            conds.equal("t.bind_id", id);

            List<WxQrcode> list = wxQrcodeService.fetchSearchByPage(0L, conds, null, 0, 0);
            if (list != null && list.size() > 0) {
                WxQrcode oldQrcode = list.get(0);
                oldQrcode.setBindId(null);
                wxQrcodeService.updateBindId(oldQrcode);
            }
        }

        WxQrcode wxQrcode = wxQrcodeService.fetchById(wxQrcodeId);

        //做2方的更新操作
        Qyuser newQyuser = new Qyuser();
        newQyuser.setId(id);
        newQyuser.setQrcode(wxQrcode.getTicket());

        WxQrcode newQrcode = new WxQrcode();
        newQrcode.setId(wxQrcodeId);
        newQrcode.setBindId(id);

        qyuserService.update(newQyuser);
        wxQrcodeService.update(newQrcode);

        retObj.put("errorNo", "0");

        return retObj;
    }

    /**
     * 设置对应、客服、药师峰值
     *
     * @return
     */
    @RequiresPermissions(value = PermissionSign.QYUSER_EDIT)
    @RequestMapping(value = "/setPeakVal", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject setPeakVal(@RequestParam Long id, @RequestParam Long peakVal) {
        JSONObject retObj = new JSONObject();
        try {
            Qyuser qyuser = qyuserService.fetchById(id);
            qyuser.setPeakVal(peakVal);
            qyuserService.updateAssigned(qyuser);
            retObj.put("errorNo", 0);
        } catch (Exception e) {
            e.printStackTrace();
            retObj.put("errorNo", 1);
        }
        return retObj;
    }
}