package com.huiju.estateagents.sample.controller;

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.StringUtils;
import com.huiju.estateagents.redpack.entity.TaH5Template;
import com.huiju.estateagents.redpack.service.ITaH5TemplateService;
import com.huiju.estateagents.sample.entity.*;
import com.huiju.estateagents.sample.service.*;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

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

    @Autowired
    public ITaH5SampleService iTaH5SampleService;

    @Autowired
    public ITaSampleContactService iTaSampleContactService;

    @Autowired
    public ITaContactService taContactService;

    @Autowired
    public ITaH5DemandService iTaH5DemandService;

    @Autowired
    public ITaNoticeService taNoticeService;

    @Autowired
    public ITaH5TemplateService taH5TemplateService;

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/channel/listH5SampleByCondition", method = RequestMethod.GET)
    public ResponseBean listH5SampleByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                String sampleName) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaH5SampleService.listH5SampleByCondition(pageNum, pageSize, sampleName);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ListH5SampleByCondition -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/admin/taH5Sample", method = RequestMethod.GET)
    public ResponseBean taH5SampleList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "sampleName", required = false) String sampleName,
                                       @RequestParam(value = "tag", required = false) String tag) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaH5Sample> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaH5Sample> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(sampleName), "sample_name", sampleName);
            queryWrapper.like(!StringUtils.isEmpty(tag), "tag", tag);
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.orderByDesc("order_no", "create_date");

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

    /**
     * 保存对象
     *
     * @param taH5Sample 实体对象
     * @return
     */
    @RequestMapping(value = "/taH5Sample", method = RequestMethod.POST)
    public ResponseBean taH5SampleAdd(@RequestBody TaH5Sample taH5Sample, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taH5Sample.setAddUser(getSysUserId(request));
            if (iTaH5SampleService.save(taH5Sample)) {
                responseBean.addSuccess(taH5Sample);
            } else {
                responseBean.addError("fail");
            }

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

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

    /**
     * 修改对象
     *
     * @param id         实体ID
     * @param taH5Sample 实体对象
     * @return
     */
    @RequestMapping(value = "/taH5Sample/{id}", method = RequestMethod.PUT)
    public ResponseBean taH5SampleUpdate(@PathVariable Integer id,
                                         @RequestBody TaH5Sample taH5Sample,
                                         HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taH5Sample.setUpdateUser(getSysUserId(request));
            taH5Sample.setUpdateDate(LocalDateTime.now());
            if (iTaH5SampleService.updateById(taH5Sample)) {
                responseBean.addSuccess(taH5Sample);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/taH5Sample/{id}", method = RequestMethod.GET)
    public ResponseBean taH5SampleGet(@PathVariable Integer id, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaH5Sample sample = iTaH5SampleService.getById(id);
            if (sample.getStatus() != 1){
                responseBean.addError("该H5样例已取消发布或已删除");
                return responseBean;
            }

            TaH5Sample taH5Sample = iTaH5SampleService.getById(id);
            QueryWrapper<TaH5Demand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sample_id", id);
            queryWrapper.ne("demand_status", CommConstant.STATUS_DELETE);
            queryWrapper.eq("org_id", getOrgId(request));
            Integer demandNum = iTaH5DemandService.count(queryWrapper);
            IPage<TaContact> taContactIPage = taContactService.taContactInfoBySampleId(String.valueOf(id), 1 , 10);
            taH5Sample.setTaContactList(taContactIPage.getRecords());
            taH5Sample.setDemandNum(demandNum);
            responseBean.addSuccess(taH5Sample);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 分页查询列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/channel/h5Sample/list", method = RequestMethod.GET)
    public ResponseBean geth5SampleList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                        @RequestParam(value = "sampleName", required = false) String sampleName,
                                        @RequestParam(value = "tag", required = false) String tag,
                                        @RequestParam(value = "status", required = false) Integer status,
                                        @RequestParam(value = "startCreateDate", required = false) String startCreateDate,
                                        @RequestParam(value = "endCreateDate", required = false) String endCreateDate) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaH5Sample> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaH5Sample> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(sampleName), "sample_name", sampleName);
            queryWrapper.like(!StringUtils.isEmpty(tag), "tag", tag);
            queryWrapper.eq(null != status, "status", status);
            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("status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("order_no", "create_date");

            IPage<TaH5Sample> result = iTaH5SampleService.page(pg, queryWrapper);
            result.getRecords().forEach(e -> {
                if (!StringUtils.isEmpty(e.getTag())) {
                    e.setTags(Arrays.asList(e.getTag().split(",")));
                }
            });
            responseBean.addSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleList -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 保存对象
     *
     * @param taH5Sample 实体对象
     * @return
     */
    @RequestMapping(value = "/channel/h5Sample/add", method = RequestMethod.POST)
    public ResponseBean AddTaH5Sample(@RequestBody TaH5Sample taH5Sample,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            List<String> tags = taH5Sample.getTags();
            taH5Sample.setTag(String.join(",", tags));
            taH5Sample.setAddUser(getSysUserId(request));
            taH5Sample.setUpdateUser(getSysUserId(request));
            taH5Sample.setCreateDate(LocalDateTime.now());
            taH5Sample.setUpdateDate(LocalDateTime.now());
            if (iTaH5SampleService.save(taH5Sample)) {
                List<TaContact> taContactList = taH5Sample.getTaContactList();
                taContactList.forEach(e -> {
                    TaSampleContact taSampleContact = new TaSampleContact();
                    taSampleContact.setContactId(e.getContactId());
                    taSampleContact.setSampleId(taH5Sample.getSampleId());
                    iTaSampleContactService.save(taSampleContact);
                });
                responseBean.addSuccess(taH5Sample);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 获取详情
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/channel/get/h5Sample/{id}", method = RequestMethod.GET)
    public ResponseBean getTaH5Sample(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        try {
            TaH5Sample taH5Sample = iTaH5SampleService.getById(id);
            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()))
                        .eq("status",CommConstant.STATUS_NORMAL));
                taH5Sample.setTaContactList(taContactList);
            }
            if (!StringUtils.isEmpty(taH5Sample.getTag())) {
                taH5Sample.setTags(Arrays.asList(taH5Sample.getTag().split(",")));
            }

            QueryWrapper<TaH5Template> taH5TemplateQueryWrapper = new QueryWrapper<>();
            taH5TemplateQueryWrapper.eq("h5_template_id", taH5Sample.getH5TemplateId());
            List<TaH5Template> taH5Templates = taH5TemplateService.list(taH5TemplateQueryWrapper);
            taH5Sample.setTaH5Template(taH5Templates);
            responseBean.addSuccess(taH5Sample);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 更新对象
     *
     * @param taH5Sample 实体对象
     * @return
     */
    @RequestMapping(value = "/channel/update/h5Sample/{id}", method = RequestMethod.PUT)
    public ResponseBean updateTaH5Sample(@PathVariable Integer id, @RequestBody TaH5Sample taH5Sample,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taH5Sample.setSampleId(id);
            List<String> tags = taH5Sample.getTags();
            if (tags.size() > 0) {
                taH5Sample.setTag(String.join(",", tags));
            } else {
                taH5Sample.setTag("");
            }
            QueryWrapper<TaSampleContact> taSampleContactQueryWrapper = new QueryWrapper<>();
            taSampleContactQueryWrapper.eq("sample_id", id);
            iTaSampleContactService.remove(taSampleContactQueryWrapper);
            taH5Sample.setUpdateUser(getSysUserId(request));
            taH5Sample.setUpdateDate(LocalDateTime.now());
            if (CollectionUtils.isNotEmpty(taH5Sample.getTaH5Template())){
                taH5Sample.setH5TemplateId(taH5Sample.getTaH5Template().get(0).getH5TemplateId());
            }else{
                taH5Sample.setH5TemplateId("");
            }
            if (iTaH5SampleService.updateById(taH5Sample)) {
                List<TaContact> taContactList = taH5Sample.getTaContactList();
                taContactList.forEach(e -> {
                    TaSampleContact taSampleContact = new TaSampleContact();
                    taSampleContact.setContactId(e.getContactId());
                    taSampleContact.setSampleId(taH5Sample.getSampleId());
                    iTaSampleContactService.save(taSampleContact);
                });
                //更新需求单中的样例名
                QueryWrapper<TaH5Demand> taH5DemandQueryWrapper = new QueryWrapper<>();
                taH5DemandQueryWrapper.eq("sample_id",id);
                List<TaH5Demand> demandList = iTaH5DemandService.list(taH5DemandQueryWrapper);
                if (demandList.size() > 0){
                    demandList.forEach(e -> {
                        e.setSampleName(taH5Sample.getSampleName());
                    });
                    iTaH5DemandService.updateBatchById(demandList);
                }
                //更新通知中的样例名
                QueryWrapper<TaNotice> taNoticeQueryWrapper = new QueryWrapper<>();
                taNoticeQueryWrapper.eq("target_id",id);
                taNoticeQueryWrapper.eq("target_type",CommConstant.NOTICE_TYPE_H5);
                List<TaNotice> noticeList = taNoticeService.list(taNoticeQueryWrapper);
                if (noticeList.size() > 0){
                    noticeList.forEach(e -> {
                        e.setTargetName(taH5Sample.getSampleName());
                    });
                    taNoticeService.updateBatchById(noticeList);
                }

                responseBean.addSuccess(taH5Sample);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }


    /**
     * 删除sample
     *
     * @return
     */
    @RequestMapping(value = "/channel/put/h5Sample/{id}", method = RequestMethod.PUT)
    public ResponseBean putTaH5Sample(@PathVariable Integer id,HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //查看是否有关联的需求单
            QueryWrapper<TaH5Demand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sample_id", id);
            queryWrapper.gt("demand_status", CommConstant.STATUS_DELETE);
            List<TaH5Demand> list = iTaH5DemandService.list(queryWrapper);
            if (list.size() > 0) {
                return ResponseBean.error("存在关联的需求单，删除失败！", ResponseBean.ERROR_UNAVAILABLE);
            }
            TaH5Sample taH5Sample = iTaH5SampleService.getById(id);
            taH5Sample.setUpdateUser(getSysUserId(request));
            taH5Sample.setUpdateDate(LocalDateTime.now());
            taH5Sample.setStatus(CommConstant.STATUS_DELETE);
            if (iTaH5SampleService.updateById(taH5Sample)) {
                responseBean.addSuccess(taH5Sample);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taH5SampleAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
