package com.cftech.member.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
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.MemberTags;
import com.cftech.member.model.TagsCards;
import com.cftech.member.service.MemberTagsService;
import com.cftech.sys.security.UserUtils;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String MEMBERTAGS_VIEW = "qy:memberTags:view"
 * 查看:public static final String MEMBERTAGS_EDIT = "qy:memberTags:edit"
 *
 * @author lisw
 * @date: 2017-09-13 14:04
 */
@Slf4j
@Controller
@RequestMapping("/a/memberTags")
public class MemberTagsController {

    public static final String MEMBERTAGS_VIEW = "qy:memberTags:view";
    public static final String MEMBERTAGS_EDIT = "qy:memberTags:edit";

    @Autowired
    private MemberTagsService memberTagsService;
    @Autowired
    private CodingruleUtils codingruleUtils;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = MEMBERTAGS_VIEW)
    @RequestMapping("/form")
    public String form(HttpServletRequest request, String id, Model model) {
        try{
            if (!StringUtils.isEmpty(id)) {
                MemberTags memberTags = memberTagsService.fetchById(id);
                model.addAttribute("data", memberTags);
                Map<String,Object> params =new HashMap<String,Object>();
                params.put("tagId",id);
                List<TagsCards> tagsCardsList = memberTagsService.fetchSearchCardTagsByPage(params);
                String ids = "";
                String names="";
                JSONObject selectCard = new JSONObject();
                if(tagsCardsList!=null && tagsCardsList.size()>0){
                    for(TagsCards tagsCards : tagsCardsList){
                        ids+=tagsCards.getCardId()+",";
                        names+=tagsCards.getCardName()+",";
                        selectCard.put(tagsCards.getCardId().toString(),tagsCards.getSort());
                    }
                    model.addAttribute("ids",ids);
                    model.addAttribute("names",names);
                    model.addAttribute("selectCard",selectCard);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return "memberTags/memberTagsform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = MEMBERTAGS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(MemberTags memberTags, Model model, HttpServletRequest request,String tagsCardJson) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        List<TagsCards> tagsCardsList = new ArrayList<TagsCards>();

        Conds conds = new Conds();
        conds.equal("memberTagsTemp.tag_code",memberTags.getTagCode());
        conds.equal("memberTagsTemp.del_flag",0);
        if(memberTags.getId()!=null){
            conds.notEqual("memberTagsTemp.id",memberTags.getId());
        }
        MemberTags memberTagsCode = memberTagsService.fetchSearchByConds(conds);
        if(memberTagsCode!=null){
            rtnJson.put("errorNo",3);
            return rtnJson;
        }
        try {
            if(!StringUtils.isEmpty(tagsCardJson)){
                JSONArray array = JSON.parseArray(tagsCardJson);
                if(array!=null && array.size()>0){
                    for(int i =0;i<array.size();i++){
                        JSONObject tagJson = array.getJSONObject(i);
                        TagsCards tagsCards = new TagsCards();
                        tagsCards.setSort(tagJson.getIntValue("sort"));
                        tagsCards.setCardId(tagJson.getLong("cardId"));
                        tagsCardsList.add(tagsCards);
                    }
                }
            }
            if (memberTags != null && memberTags.getId() != null) {
                memberTags.setUpdateBy(UserUtils.getUser().getId());
                memberTagsService.updateBatchTagCard(memberTags,tagsCardsList);
                rtnJson.put("errorNo", 0);
            } else {
                memberTags.setNumber(codingruleUtils.getNumber(accountsId, MemberTags.class.getName()));
                memberTags.setAccountsId(accountsId);
                memberTags.setDelFlag(false);
                memberTags.setAccountsId(UserUtils.getmpaccounts(request));
                memberTags.setCreateBy(UserUtils.getUser().getId());
                memberTags.setUpdateBy(UserUtils.getUser().getId());
                memberTagsService.saveBatchTagCard(memberTags,tagsCardsList);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = MEMBERTAGS_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, MemberTags memberTags, HttpServletRequest request,String cardName) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("memberTagsTemp.del_flag", Constants.DEL_FLAG_0);
        conds.equal("memberTagsTemp.accounts_id", accountsId);
        if (!StringUtils.isEmpty(memberTags.getNumber())) {
            conds.like("memberTagsTemp.number", memberTags.getNumber());
        }
        if (!StringUtils.isEmpty(memberTags.getTagName())) {
            conds.like("memberTagsTemp.tag_name", memberTags.getTagName());
        }
        if(!StringUtils.isEmpty(memberTags.getTagCode())){
            conds.like("memberTagsTemp.tag_code", memberTags.getTagCode());
        }
        if(!StringUtils.isEmpty(cardName)){
            conds.like("memberTagsTemp.cardNames", cardName);
        }
        Sort sort = new Sort("memberTagsTemp.create_time", OrderType.DESC);

        List<MemberTags> list = memberTagsService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
        Integer counts = memberTagsService.count(conds);
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("iTotalRecords", counts);
        rtnJson.put("iTotalDisplayRecords", counts);
        rtnJson.put("aaData", list);
        return rtnJson;
    }

    //删除数据
    @RequiresPermissions(value = MEMBERTAGS_EDIT)
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(String id) {
        JSONObject rtnJosn = new JSONObject();
        try {
            memberTagsService.delete(id);
            rtnJosn.put("errorNo", 0);
        } catch (Exception e) {
            rtnJosn.put("errorNo", 1);
        }
        return rtnJosn;
    }

}
