package com.ffii.tbms.api.web;

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

import com.ffii.core.utils.CriteriaUtils;
import com.ffii.core.utils.NumberUtils;
import com.ffii.core.utils.Params;
import com.ffii.core.utils.web.ServletRequestUtils;
import com.ffii.core.web.AbstractController;
import com.ffii.core.web.view.json.JsonView;
import com.ffii.tbms.api.service.AuthenticationService;
import com.ffii.tbms.api.service.CustomerApiService;
import com.ffii.tbms.api.service.OrderApiService;
import com.ffii.tbms.customer.Customer;
import com.ffii.tbms.customer.service.CustomerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value = "api/customer/")
/**
 * OrderApiController
 */
public class CustomerApiController extends AbstractController {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    CustomerApiService service;

    @Autowired
    OrderApiService orderApiService;

     
    @RequestMapping(value = "save", method = { RequestMethod.GET, RequestMethod.POST })
    public String saveCustomer(Model model, @RequestParam String deviceId, @RequestParam String token, HttpServletRequest request,
            @RequestParam(defaultValue = "-1") Integer id) {

        Map<String, Object> userData = authenticationService.findUserByAccessToken(deviceId, token);
        if (userData == null) {
            model.addAllAttributes(authenticationService.getNoUserFoundMap());
            return JsonView.NAME;
        }

        boolean haveAuth = authenticationService.haveAuth(userData.get("id"),"CUSTOMER_MAINTAIN");
        if (!haveAuth) {
            model.addAllAttributes(authenticationService.getNoAuthFoundMap());
            return JsonView.NAME;
        }

        Customer instance;
        if (id > 0) {
            instance = service.find(id);
            logger.info("meeting found");
        } else {
            instance = new Customer();
            instance.setSysGroupId(NumberUtils.toInt(userData.get("sysGroupId"),0));
        }

        ServletRequestUtils.doBind(request, instance, null);
        id = service.saveOrUpdate(instance);

        logger.info("Meeting Save: "+request.getParameter("date"));

        model.addAttribute(Params.ID, id);
        model.addAttribute(Params.SUCCESS, Boolean.TRUE);


        return JsonView.NAME;
    }

    @RequestMapping(value = "list", method = { RequestMethod.GET, RequestMethod.POST })
    public String listCustomer(Model model, @RequestParam String deviceId, @RequestParam String token,
            HttpServletRequest request) throws Exception {

        Map<String, Object> userData = authenticationService.findUserByAccessToken(deviceId, token);
        if (userData == null) {
            model.addAllAttributes(authenticationService.getNoUserFoundMap());
            return JsonView.NAME;
        }

        boolean haveAuth = authenticationService.haveAuth(userData.get("id"),"CUSTOMER_MAINTAIN");
        if (!haveAuth) {
            model.addAllAttributes(authenticationService.getNoAuthFoundMap());
            return JsonView.NAME;
        }

        final Map<String, Object> args = new HashMap<String, Object>();
        args.put("sysGroupId", userData.get("sysGroupId"));

        CriteriaUtils.addInteger(request, args, Params.ID);
        CriteriaUtils.addStringLike(request, args, "searchStr");

        if(args.containsKey("searchStr") && args.get("searchStr").toString().length()>=2){
            args.put("_searchStr", args.get("searchStr"));
            CriteriaUtils.addString(request, args, "searchStr");
        }else{
            model.addAttribute(Params.AUTH, Boolean.TRUE);
            model.addAttribute(Params.SUCCESS, Boolean.TRUE);
            model.addAttribute(Params.RECORDS, null);
            return JsonView.NAME;
        }
        
        logger.info("list: args: " + args);
        final List<Map<String, Object>> records = service.searchCustomerList(args);
        logger.info("list: records: " + records);

        model.addAttribute(Params.AUTH, Boolean.TRUE);
        model.addAttribute(Params.SUCCESS, Boolean.TRUE);
        model.addAttribute(Params.RECORDS, records);

        return JsonView.NAME;
    }

    
    @RequestMapping(value = "load", method = { RequestMethod.GET, RequestMethod.POST })
    public String loadCustomer(Model model, @RequestParam String deviceId, @RequestParam String token,
            HttpServletRequest request) throws Exception {

        Map<String, Object> userData = authenticationService.findUserByAccessToken(deviceId, token);
        if (userData == null) {
            model.addAllAttributes(authenticationService.getNoUserFoundMap());
            return JsonView.NAME;
        }

        boolean haveAuth = authenticationService.haveAuth(userData.get("id"),"CUSTOMER_MAINTAIN");
        if (!haveAuth) {
            model.addAllAttributes(authenticationService.getNoAuthFoundMap());
            return JsonView.NAME;
        }

        final Map<String, Object> args = new HashMap<String, Object>();

        CriteriaUtils.addInteger(request, args, Params.ID);
        CriteriaUtils.addInteger(request, args, "custId");
        
        logger.info("load: args: " + args);

        Map<String, Object> data = service.loadCustomer(args);
        logger.info("load: data: " + data);

        List<Map<String, Object>> orderList = orderApiService.search(args);

        model.addAttribute(Params.AUTH, Boolean.TRUE);
        model.addAttribute(Params.SUCCESS, Boolean.TRUE);
        model.addAttribute(Params.DATA, data);
        model.addAttribute("orderList", orderList);

        return JsonView.NAME;
    }

 
    @RequestMapping(value = "combo.json", method = { RequestMethod.GET, RequestMethod.POST })
    public String getCustomerComboJson(Model model, @RequestParam String deviceId, @RequestParam String token, HttpServletRequest request) throws Exception {

        Map<String, Object> userData = authenticationService.findUserByAccessToken(deviceId, token);
        if (userData == null) {
            model.addAllAttributes(authenticationService.getNoUserFoundMap());
            return JsonView.NAME;
        }

        Map<String, Object> args = new HashMap<String, Object>();

        CriteriaUtils.addInteger(request, args, Params.ID);
        CriteriaUtils.addStringLike(request, args, Params.QUERY);
        CriteriaUtils.addInteger(request, args, "deptId");
        args.put("sysGroupId", userData.get("sysGroupId"));

        if(args.containsKey("query") && args.get("query").toString().length()>=2){
            args.put("_query", args.get("query"));
            CriteriaUtils.addStringLike(request, args, "query");
            List<Map<String, Object>> records = service.searchForCombo(args);
            model.addAttribute(Params.RECORDS, records);
        }else if(args.containsKey("id")){
            List<Map<String, Object>> records = service.searchForCombo(args);
            if(records != null && records.size()>0)
                model.addAttribute(Params.DATA, records.get(0));
            else
                model.addAttribute(Params.DATA, null);
        }else{
            List<Map<String, Object>> records = service.searchForCombo(args);
            model.addAttribute(Params.AUTH, Boolean.TRUE);
            model.addAttribute(Params.SUCCESS, Boolean.TRUE);
            model.addAttribute(Params.RECORDS, records);
            return JsonView.NAME;
        }

        model.addAttribute(Params.AUTH, Boolean.TRUE);
        model.addAttribute(Params.SUCCESS, Boolean.TRUE);

        return JsonView.NAME;
    }

}