package com.cftech.workshop.details.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.workshop.detail_log.model.Detail_log;
import com.cftech.workshop.detail_log.service.Detail_logService;
import com.cftech.workshop.details.model.Details;
import com.cftech.workshop.details.service.DetailsService;
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.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import com.cftech.workshop.meeting.model.Meeting;
import com.cftech.workshop.meeting.service.MeetingService;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

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


/**
 * Controller
 * <p>
 * 权限字符串说明:
 * 查看:public static final String DETAILS_VIEW = "qy:details:view"
 * 查看:public static final String DETAILS_EDIT = "qy:details:edit"
 *
 * @author byj
 * @date: 2018-07-06 10:27
 */
@Slf4j
@Controller
@RequestMapping("/a/details")
public class DetailsController {

    public static final String DETAILS_VIEW = "qy:details:view";
    public static final String DETAILS_EDIT = "qy:details:edit";

    @Autowired
    private DetailsService detailsService;
    @Autowired
    private CodingruleUtils codingruleUtils;

    @Autowired
    private MeetingService meetingService;

    @Autowired
    private Detail_logService detail_logService;


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

    //编辑页面（新增、修改）
    @RequiresPermissions(value = DETAILS_VIEW)
    @RequestMapping(value = "/form")
    public String form(HttpServletRequest request, String id, Model model,String meetingId ,String member_uid) { //id:研讨会ID
        model.addAttribute("member_uid",member_uid);
        if (!StringUtils.isEmpty(meetingId)&&!StringUtils.isEmpty(member_uid)) {
            try {
                Conds conds = new Conds();
                conds.equal("meeting_id", meetingId);
                conds.equal("memberUid",member_uid);
                Sort sort = new Sort("create_time",OrderType.DESC);
                List<Details> list=detailsService.fetchSearchByPage(conds,sort,0,0);
                if(list!=null && list.size()>0){
                    for(Details li:list){
                        String details = HtmlUtils.htmlUnescape(li.getDetailsinfo());
                        if(details!=null){
                            JSONObject object = JSONObject.parseObject(details);
                            model.addAttribute("desc",object.getString("desc"));
                            if(object.getString("isHotel").equals("0")){ //如果选择酒店服务

                                JSONObject hotelObject =JSON.parseObject(object.getString("hotel"));
                                model.addAttribute("detailsObject",hotelObject);
                            }
                            if(object.getString("isRelay").equals("0")){ //如果选择接送服务
                                JSONObject relayAray = JSON.parseObject(object.getString("relay")); //接
                                if(!StringUtils.isEmpty(relayAray)){
                                    JSONObject detailsplane = JSON.parseObject(relayAray.getString("plane"));
                                    JSONObject detailshigh = JSON.parseObject(relayAray.getString("high"));
                                    model.addAttribute("detailsplane",detailsplane);
                                    model.addAttribute("detailshigh",detailshigh);
                                    String  arrivetime= relayAray.getString("arrivetime");  //到站时间班次
                                    if(!StringUtils.isEmpty(arrivetime)){
                                        model.addAttribute("arrivetime",arrivetime);
                                    }
                                    String shift = relayAray.getString("shift");
                                    if(!StringUtils.isEmpty(shift)){
                                        model.addAttribute("shift",shift);
                                    }
                                }

                                JSONObject relayAray1 = JSON.parseObject(object.getString("send"));  //送
                                if(!StringUtils.isEmpty(relayAray1)){
                                    JSONObject detailsplane1 = JSON.parseObject(relayAray1.getString("plane"));
                                    JSONObject detailshigh1 = JSON.parseObject(relayAray1.getString("high"));
                                    model.addAttribute("detailshigh1",detailshigh1);
                                    model.addAttribute("detailsplane1",detailsplane1);
                                    String arrivetime1 = relayAray1.getString("arrivetime1");//到站时间班次
                                    if(!StringUtils.isEmpty(arrivetime1)){
                                        model.addAttribute("arrivetime1",arrivetime1);
                                    }
                                    String shift1 = relayAray1.getString("shift1");
                                    if(!StringUtils.isEmpty(shift1)){
                                        model.addAttribute("shift1",shift1);
                                    }
                                }
                            }
                            model.addAttribute("detailsinfo",details);
                        }
                    }
                }else{
                    model.addAttribute("detailsinfo","{}");
                }
                Meeting meeting = meetingService.fetchById(meetingId);
                String service = meeting.getService();
                if(!StringUtils.isEmpty(service)){
                    service=HtmlUtils.htmlUnescape(service);
                    JSONObject object = JSONObject.parseObject(service);
                    if(object.getString("isHotel").equals("0")){
                        JSONArray array = JSON.parseArray(object.getString("hotel"));
                        model.addAttribute("hotel",array);
                    }
                    if(object.getString("isEat").equals("0")){
                        JSONArray array = JSON.parseArray(object.getString("eat"));
                        model.addAttribute("eat",array);
                    }
                    if(object.getString("isRelay").equals("0")){
                        JSONObject relayObject = JSON.parseObject(object.getString("relay"));
                        JSONArray array = JSON.parseArray(relayObject.getString("plane"));
                        JSONArray array1 = JSON.parseArray(relayObject.getString("high"));
                        model.addAttribute("plane",array);
                        model.addAttribute("high",array1);
                        model.addAttribute("relay",relayObject);
                    }
                    if(object.getString("isTake").equals("0")){
                        JSONArray array = JSON.parseArray(object.getString("take"));
                        model.addAttribute("take",array);
                    }
                    if(object.getString("isfactory").equals("0")){
                        JSONArray array = JSON.parseArray(object.getString("factory"));
                        model.addAttribute("factory",array);
                    }
                    model.addAttribute("service",object);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            model.addAttribute("meetingId",meetingId);
        }

        return "details/detailsform";
    }

    //提交数据（新增、修改）
    @RequiresPermissions(value = DETAILS_EDIT)
    @RequestMapping("/formData")
    @ResponseBody
    public JSONObject formData(Details details, Model model, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        JSONObject rtnJson = new JSONObject();
        Conds cd = new Conds();
        cd.equal("memberUid",details.getMemberUid());
        cd.equal("meeting_id",details.getMeeting_id());
        Details d = detailsService.fetchSearchByConds(cd);
        if(d!=null){
            details.setId(d.getId());
        }
        try {
            if (details != null && details.getId() != null) {
                details.setUpdateBy(UserUtils.getUser().getId());
                detailsService.update(details);
                Detail_log detail_log = new Detail_log();
                detail_log.setMeetingId(details.getMeeting_id());
                detail_log.setDetaillog(details.getDetailsinfo());
                detail_log.setTime(details.getUpdateTime());
                detail_log.setIsadmin(String.valueOf(1));
                detail_log.setMemberUid(details.getMemberUid());
                detail_logService.save(detail_log);
                rtnJson.put("errorNo", 0);
            } else {
                details.setNumber(codingruleUtils.getNumber(accountsId, Details.class.getName()));
                details.setAccountsId(accountsId);
                details.setDelFlag(false);
                details.setAccountsId(UserUtils.getmpaccounts(request));
                details.setCreateBy(UserUtils.getUser().getId());
                details.setUpdateBy(UserUtils.getUser().getId());
                detailsService.save(details);
                rtnJson.put("errorNo", 2);
            }
        } catch (Exception e) {
            rtnJson.put("errorNo", 1);
        }
        return rtnJson;
    }

    //获取列表数据
    @RequiresPermissions(value = DETAILS_VIEW)
    @RequestMapping(value = "/listData")
    @ResponseBody
    public JSONObject listData(int iDisplayStart, int iDisplayLength, Details details, HttpServletRequest request) {
        Long accountsId = UserUtils.getmpaccounts(request);
        Conds conds = new Conds();
        conds.equal("del_flag", Constants.DEL_FLAG_0);
        conds.equal("accounts_id", accountsId);
        if (!StringUtils.isEmpty(details.getNumber())) {
            conds.like("number", details.getNumber());
        }
        if (!StringUtils.isEmpty(details.getMeeting_id())) {
            conds.equal("meeting_id", details.getMeeting_id());
        }
        if (!StringUtils.isEmpty(details.getMemberUid())) {
            conds.equal("open_id", details.getMemberUid());
        }
        Sort sort = new Sort("create_time", OrderType.DESC);

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

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

}
