package com.cftech.member.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
import com.cftech.core.annotation.CSRFTokenRef;
import com.cftech.core.config.MpGlobalConfig;
import com.cftech.core.poi.ExcelKit;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.member.model.Member;
import com.cftech.member.model.MemberDto;
import com.cftech.member.service.MemberService;
import com.cftech.sys.filter.McCsrfTokenRepository;
import com.cftech.sys.model.User;
import com.cftech.sys.security.UserUtils;
import com.cftech.workshop.workshop.model.Workshop;
import com.cftech.workshop.workshop.service.WorkshopService;
import com.ctc.wstx.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.HTTP;
import org.owasp.esapi.ESAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String MEMBER_VIEW = "qy:member:view"
 * 查看:public static final String MEMBER_EDIT = "qy:member:edit"
 *
 * @author lisw
 * @date: 2017-08-24 17:31
 */
@Slf4j
@Controller
@RequestMapping("/a/member")
public class MemberController {

    public static final String MEMBER_VIEW = "qy:member:view";
    public static final String MEMBER_EDIT = "qy:member:edit";

//    @Autowired
//    private McCsrfTokenRepository mcCsrfTokenRepository;

    @Autowired
    private MemberService memberService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private WorkshopService workshopService;

    //列表页面
    @RequiresPermissions(value = MEMBER_VIEW)
    @RequestMapping("/listpl")
    public String listpl(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "member/memberlistpl";
    }

    //列表页面
    @RequiresPermissions(value = MEMBER_VIEW)
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        Long accountId = UserUtils.getmpaccounts(request);
        model.addAttribute("accountId", accountId);
        return "member/memberlist";
    }

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MEMBER_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        if (!StringUtils.isEmpty(id)) {
            Member member = memberService.fetchById(id);
            model.addAttribute("data", member);
        }
        return "member/memberform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = MEMBER_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Member member, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        try {
            if (member != null && member.getId() != null) {
                member.setUpdateBy(UserUtils.getUser().getId());
                memberService.update(member);
                rtnJson.put("errorNo", 0);
            } else {
                member.setNumber(codingruleUtils.getNumber(accountsId, Member.class.getName()));
                member.setAccountsId(accountsId);
                member.setDelFlag(false);
                member.setAccountsId(UserUtils.getmpaccounts(request));
                member.setCreateBy(UserUtils.getUser().getId());
                member.setUpdateBy(UserUtils.getUser().getId());
                memberService.save(member);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @CSRFTokenRef
    @RequiresPermissions(value = MEMBER_VIEW)
    @RequestMapping(value = "/listData",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Member member, HttpServletRequest request,HttpServletResponse response) {
        Long accountsId = UserUtils.getmpaccounts(request);
        String res = ESAPI.encoder().decodeForHTML("https://www.michang-tech.com.cn/aidea/static/mp/aidea/meeting-intro.html?appid=wxa53abdf500a8ee6d&amp;id=6");
        System.out.print(res);
        /*Conds conds = new Conds();
        conds.equal("member.del_flag", Constants.DEL_FLAG_0);
        conds.equal("member.accounts_id", accountsId);
        if (!StringUtils.isEmpty(member.getNumber())) {
            conds.like("member.number", member.getNumber());
        }
        if (!StringUtils.isEmpty(member.getName())) {
            conds.like("member.name", member.getName());
        }
        if (!StringUtils.isEmpty(member.getPhone())) {
            conds.like("member.phone", member.getPhone());
        }
        if (!StringUtils.isEmpty(member.getCardid())) {
            conds.like("member.cardid", member.getCardid());
        }
        Sort sort = new Sort("member.create_time", OrderType.DESC);

        List<Member> list = memberService.fetchSearchByPageServer(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = memberService.countServer(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);*/

        Conds conds = new Conds();
        conds.equal("m.del_flag", Constants.DEL_FLAG_0);

//        if(member.getStatus().equals("1")){  //注册会员
//            conds.isNull("m.status");
//        }else if(member.getStatus().equals("2")){ //虚拟会员
//            conds.equal("m.status",1);
//        }
//        if (!StringUtils.isEmpty(member.getCompan())) {
//            conds.like("m.compan", member.getCompan());
//        }

        if (!StringUtils.isEmpty(member.getName())) {
            conds.like("CONVERT(AES_DECRYPT(m.name,'aideakey') USING UTF8)", member.getName());
        }
        if (!StringUtils.isEmpty(member.getPhone())){
            conds.like("CONVERT(AES_DECRYPT(m.phone,'aideakey') USING UTF8)",member.getPhone());
        }


        Sort sort = new Sort("m.create_time", OrderType.DESC);

        List<MemberDto> list = memberService.selectmemberDto(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = memberService.selectmemberDtoCount(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = MEMBER_EDIT)
    @RequestMapping(value="/delete",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject delete(String id,HttpServletRequest request,HttpServletResponse response) {
        JSONObject rtnJosn = new JSONObject();
        try {
            memberService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

    //删除数据
    @RequiresPermissions(value = MEMBER_EDIT)
    @RequestMapping(value="/addMember",method = {RequestMethod.POST})
    @ResponseBody
    public JSONObject addMember(String code,HttpServletRequest request,HttpServletResponse response) {
        JSONObject rtnJosn = new JSONObject();
        Long accountsId = UserUtils.getmpaccounts(request);
        rtnJosn.put("errorNo", 0);
        try {
            if(!StringUtils.isEmpty(code)){
                Conds conds = new Conds();
                conds.equal("w.invitcode",code);
                conds.equal("w.status",0);
                conds.equal("w.del_flag",0);
                Workshop workshop = workshopService.fetchSearchByConds(conds);
                if(workshop!=null){
                    Member member = new Member();
                    member.setStatus("1");
                    //member.setOilSum("0");
                    member.setNumber(codingruleUtils.getNumber(accountsId, Member.class.getName()));
                    //member.setMember_uid(UUID.randomUUID().toString());
                    member.setName(workshop.getFirst_name());
                    member.setPhone(workshop.getPhone());
                    member.setPosition(workshop.getPosition());
                    member.setCompan(workshop.getOrganization());
                    member.setInvitcode(code);
                    member.setAccountsId(accountsId);
                    memberService.save(member);
                    //workshop.setMember_uid(member.getMember_uid());
                    workshop.setStatus("1");
                    workshopService.update(workshop);
                }else{
                    rtnJosn.put("errorNo", 2);//邀请码无效
                }


            }else{
                rtnJosn.put("errorNo", 2);//邀请码为空
            }
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);//系统异常
        }
        return rtnJosn;
    }

    @RequestMapping("/exportExcel")
    @RequiresPermissions(value = MEMBER_VIEW)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response,Member member) throws ParseException {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("m.del_flag", Constants.DEL_FLAG_0);

        if (!StringUtils.isEmpty(member.getName())){
            conds.like("CONVERT(AES_DECRYPT(m.name,'aideakey') USING UTF8)", member.getName());
        }

        if (!StringUtils.isEmpty(member.getPhone())){
            conds.like("CONVERT(AES_DECRYPT(m.phone,'aideakey') USING UTF8)",member.getPhone());
        }

        Sort sort = new Sort("m.create_time", OrderType.DESC);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<MemberDto> list = memberService.selectmemberDto(conds, sort, 0, 0);
        if (list.size() > 0) {
            for (MemberDto memberDto : list) {
//                if(memberDto.get==null){
//                    memberDto.setStatus("注册会员");
//                    if(memberDto.getSex().equals("1")){
//                        memberDto.setSex("男");
//                    }else if(memberDto.getSex().equals("0")){
//                        memberDto.setSex("女");
//                    }
//                }else{
//                    memberDto.setStatus("虚拟会员");
//                }
                if ("1".equals(memberDto.getSex())) {
                    memberDto.setSex("男");
                } else if ("0".equals(memberDto.getSex())) {
                    memberDto.setSex("女");
                }
                if ("1".equals(memberDto.getSource())) {
                    memberDto.setSource("普通关注");
                } else if ("2".equals(memberDto.getSource())) {
                    memberDto.setSource("药师二维码");
                } else if ("3".equals(memberDto.getSource())) {
                    memberDto.setSource("客服二维码");
                }else if("4".equals(memberDto.getSource())){
                    memberDto.setSource("医生二维码");
                }else if("5".equals(memberDto.getSource())){
                    memberDto.setSource("组织二维码");
                }else {
                    memberDto.setSource("");
                }
                Date parse = simpleDateFormat.parse(memberDto.getCreateTime());
                memberDto.setCreateTime(simpleDateFormat.format(parse));

            }

        }
        // 生成Excel并使用浏览器下载
        ExcelKit.$Export(MemberDto.class, response).toExcel(list, "会员信息");
    }
}
