package com.huiju.estateagents.sample.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.common.SMSUtils;
import com.huiju.estateagents.common.StringUtils;
import com.huiju.estateagents.entity.SysSmsSetting;
import com.huiju.estateagents.mapper.SysSmsSettingMapper;
import com.huiju.estateagents.sample.entity.TaContact;
import com.huiju.estateagents.sample.entity.TaH5Demand;
import com.huiju.estateagents.sample.entity.TaH5Sample;
import com.huiju.estateagents.sample.entity.TaSampleContact;
import com.huiju.estateagents.sample.service.ITaContactService;
import com.huiju.estateagents.sample.service.ITaH5DemandService;
import com.huiju.estateagents.sample.service.ITaH5SampleService;
import com.huiju.estateagents.sample.service.ITaSampleContactService;
import com.huiju.estateagents.service.ITaOrgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
    * 需求单表  前端控制器
    * </p>
 *
 * @author fxf
 * @since 2020-03-18
 */
@RestController
@RequestMapping("/api")
public class TaH5DemandController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaH5DemandController.class);

    @Autowired
    public ITaH5DemandService iTaH5DemandService;

    @Autowired
    public ITaH5SampleService iTaH5SampleService;

    @Autowired
    private ITaSampleContactService iTaSampleContactService;

    @Autowired
    private ITaContactService taContactService;

    @Autowired
    private ITaOrgService iTaOrgService;

    @Autowired
    SysSmsSettingMapper sysSmsSettingMapper;

    @Autowired
    SMSUtils smsUtils;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/admin/taH5Demand",method= RequestMethod.GET)
    public ResponseBean taH5DemandList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                       @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                       @RequestParam(value ="sampleName", required = false) String sampleName,
                                       @RequestParam(value ="orderer", required = false) String orderer,
                                       @RequestParam(value ="phone", required = false) String phone,
                                       @RequestParam(value ="sampleId", required = false) Integer sampleId,
                                       @RequestParam(value ="startCreateDate", required = false) String startCreateDate,
                                       @RequestParam(value ="endCreateDate", required = false) String endCreateDate,
                                       @RequestParam(value ="demandStatus", required = false) String demandStatus,
                                       HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
		    IPage<TaH5Demand> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaH5Demand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_id", getOrgId(request));
            queryWrapper.eq(sampleId != null,"sample_id", sampleId);
            queryWrapper.ne("demand_status", CommConstant.STATUS_DELETE);
            queryWrapper.like(!StringUtils.isEmpty(sampleName),"sample_name", sampleName);
            queryWrapper.like(!StringUtils.isEmpty(orderer),"orderer", orderer);
            queryWrapper.like(!StringUtils.isEmpty(phone),"phone", phone);
            queryWrapper.eq(!StringUtils.isEmpty(demandStatus),"demand_status", demandStatus);
            queryWrapper.gt(!StringUtils.isEmpty(startCreateDate),"create_date", startCreateDate);
            queryWrapper.lt(!StringUtils.isEmpty(endCreateDate),"create_date", endCreateDate);
            queryWrapper.orderByDesc("create_date");

            IPage<TaH5Demand> result = iTaH5DemandService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     * @param taH5Demand 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taH5Demand",method= RequestMethod.POST)
    public ResponseBean taH5DemandAdd(@RequestBody TaH5Demand taH5Demand, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taH5Demand.setOrgId(getOrgId(request));
            taH5Demand.setOrgName(iTaOrgService.getById(getOrgId(request)).getName());
            taH5Demand.setDemandStatus(CommConstant.STATUS_NORMAL);
            taH5Demand.setCreateDate(LocalDateTime.now());
            taH5Demand.setUpdateDate(LocalDateTime.now());
            if (iTaH5DemandService.save(taH5Demand)){
                responseBean.addSuccess(taH5Demand);
            }else {
                responseBean.addError("fail");
            }
            TaH5Sample taH5Sample = iTaH5SampleService.getById(taH5Demand.getSampleId());
            QueryWrapper<TaSampleContact> queryWrapper = new QueryWrapper();
            queryWrapper.eq("sample_id",taH5Sample.getSampleId());
            List<TaSampleContact> sampleContactList = iTaSampleContactService.list(queryWrapper);
            if (sampleContactList.size() > 0) {
                List<TaContact> taContactList = taContactService.list(new QueryWrapper<TaContact>().in("contact_id", sampleContactList.stream().map(TaSampleContact::getContactId).collect(Collectors.toList())));
                taH5Sample.setTaContactList(taContactList);
                String[] smsParams = {taH5Sample.getSampleName(), taH5Demand.getOrderer() + "-" + taH5Demand.getPhone()};
                for (TaContact taContact : taContactList){
                    sendSmsMessage(taContact.getPhone(), CommConstant.MESSAGE_CONTENT_OF_DEMAND, smsParams);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ResponseBody
    @RequestMapping(value="/taH5Demand/{id}", method= RequestMethod.DELETE)
    public ResponseBean taH5DemandDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(iTaH5DemandService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id批量删除对象
     */
    @ResponseBody
    @RequestMapping(value="/admin/batchDelTaH5Demands", method= RequestMethod.PUT)
    public ResponseBean taH5DemandBatchDelete(@RequestBody TaH5Demand taH5Demand){
        ResponseBean responseBean = new ResponseBean();
        List<Integer> demandIds = new ArrayList<>();
        try {
            int successNum = 0;
            int failNum = 0;
            for (TaH5Demand info : taH5Demand.getTaH5Demands()){
                TaH5Demand h5Demand = iTaH5DemandService.getById(info.getDemandId());
                if (CommConstant.DEMAND_STATUS_INVALID.equals(h5Demand.getDemandStatus()) || CommConstant.DEMAND_STATUS_SUBMIT.equals(h5Demand.getDemandStatus())){
                    h5Demand.setDemandStatus(CommConstant.STATUS_DELETE);
                    iTaH5DemandService.updateById(h5Demand);
                    successNum++;
                }else{
                    failNum++;
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("successNum",successNum);
            map.put("failNum",failNum);
            responseBean.addSuccess(map);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param taH5Demand 实体对象
     * @return
     */
    @RequestMapping(value="/admin/taH5Demand/{id}",method= RequestMethod.PUT)
    public ResponseBean taH5DemandUpdate(@PathVariable Integer id,
                                        @RequestBody TaH5Demand taH5Demand){
        ResponseBean responseBean = new ResponseBean();
        try {
            if (StringUtils.isEmpty(taH5Demand.getDemandContent())){
                responseBean.addError("请填写需求内容");
                return responseBean;
            }
            taH5Demand.setDemandId(id);
            taH5Demand.setUpdateDate(LocalDateTime.now());
            if (iTaH5DemandService.updateById(taH5Demand)){
                responseBean.addSuccess(taH5Demand);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @RequestMapping(value="/admin/taH5Demand/{id}",method= RequestMethod.GET)
    public ResponseBean taH5DemandGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaH5DemandService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 获取h5需求清单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/channel/taH5Demand",method= RequestMethod.GET)
    public ResponseBean getH5DemandList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                        @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                        @RequestParam(value ="sampleName",required = false) String sampleName,
                                        @RequestParam(value ="orgName",required = false) String orgName,
                                        @RequestParam(value ="orderer",required = false) String orderer,
                                        @RequestParam(value ="phone",required = false) String phone,
                                        @RequestParam(value ="demandStatus",required = false) Integer demandStatus,
                                        @RequestParam(value ="startCreateDate",required = false) String startCreateDate,
                                        @RequestParam(value ="endCreateDate",required = false) String endCreateDate,
                                       HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaH5Demand> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaH5Demand> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(sampleName),"sample_name",sampleName);
            queryWrapper.like(!StringUtils.isEmpty(orgName),"org_name",orgName);
            queryWrapper.like(!StringUtils.isEmpty(orderer),"orderer",orderer);
            queryWrapper.like(!StringUtils.isEmpty(phone),"phone",phone);
            queryWrapper.eq(null != demandStatus,"demand_status",demandStatus);
            queryWrapper.ge(!StringUtils.isEmpty(startCreateDate),"date_format(create_date,'%Y-%m-%d')",startCreateDate);
            queryWrapper.le(!StringUtils.isEmpty(endCreateDate),"date_format(create_date,'%Y-%m-%d')",endCreateDate);
            queryWrapper.gt("demand_status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("create_date");

            IPage<TaH5Demand> result = iTaH5DemandService.page(pg, queryWrapper);
            responseBean.addSuccess(result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 批量删除需求单
     * @return
     */
    @RequestMapping(value="/channel/taH5Demand/batch",method= RequestMethod.PUT)
    public ResponseBean batchUpdateH5DemandList(@RequestBody String ids,
                                        HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            int successNum = 0;
            int failNum = 0;
            JSONArray jsonArray = JSONObject.parseObject(ids).getJSONArray("ids");
            for (Object id : jsonArray) {
                TaH5Demand h5Demand = iTaH5DemandService.getById((Integer) id);
                if (CommConstant.DEMAND_STATUS_INVALID.equals(h5Demand.getDemandStatus())){
                    h5Demand.setDemandStatus(CommConstant.STATUS_DELETE);
                    iTaH5DemandService.updateById(h5Demand);
                    successNum++;
                }else{
                    failNum++;
                }
            }
            Map<String,Object> map = new HashMap<>();
            map.put("successNum",successNum);
            map.put("failNum",failNum);
            responseBean.addSuccess(map);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("taH5DemandList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 获取需求单详情
     * @return
     */
    @RequestMapping(value="/channel/taH5Demand/{id}",method= RequestMethod.GET)
    public ResponseBean getH5Demand(@PathVariable Integer id, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaH5DemandService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getH5Demand -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 更新需求单详情
     * @return
     */
    @RequestMapping(value="/channel/taH5Demand/update/{id}",method= RequestMethod.PUT)
    public ResponseBean updateH5Demand(@PathVariable Integer id,@RequestBody TaH5Demand taH5Demand, HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        try {
            taH5Demand.setCreateDate(null);
            taH5Demand.setDemandId(id);
            taH5Demand.setUpdateDate(LocalDateTime.now());
            responseBean.addSuccess(iTaH5DemandService.updateById(taH5Demand));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("getH5Demand -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    private String sendSmsMessage(String tel, String type, String[] params) {
        if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(type)) {
            return "短信发送失败: 没有手机号或者短信模板";
        }

        QueryWrapper<SysSmsSetting> query = new QueryWrapper<>();
        query.eq("sms_type", type);
        query.eq("status", CommConstant.STATUS_NORMAL);
        query.last("limit 1");

        SysSmsSetting smsSetting = sysSmsSettingMapper.selectOne(query);
        if (null == smsSetting) {

            // TODO 写消息发送日志

            return "没有设置有效的【" + type + "】短信模板";
        }

        boolean success = smsUtils.sendMessage(smsSetting.getTplCode(), tel, params);

        // TODO 写消息发送日志

        return success ? null : "短信发送失败";
    }
}
