package com.yunzhi.marketing.sample.controller;

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.yunzhi.marketing.base.BaseController;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.sample.entity.TaContact;
import com.yunzhi.marketing.sample.service.ITaContactService;
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.List;


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

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

    @Autowired
    public ITaContactService iTaContactService;


    /**
     * 条件查询联系人列表
     *
     * @param pageNum
     * @param pageSize
     * @param contactName
     * @param telephone
     * @param phone
     * @param job
     * @return
     */
    @RequestMapping(value = "/channel/listContactByCondition", method = RequestMethod.GET)
    public ResponseBean listContactByCondition(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                               String contactName, String telephone, String phone, String job, String appellation, String contentType) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaContact> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaContact> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(contactName), "contact_name", contactName);
            queryWrapper.like(!StringUtils.isEmpty(telephone), "telephone", telephone);
            queryWrapper.like(!StringUtils.isEmpty(phone), "phone", phone);
            queryWrapper.like(!StringUtils.isEmpty(job), "job", job);
            queryWrapper.like(!StringUtils.isEmpty(appellation), "appellation", appellation);
            queryWrapper.like(!StringUtils.isEmpty(contentType), "contact_type", contentType);
            queryWrapper.ne("status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("order_no", "create_date");

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

    /**
     * 保存对象
     *
     * @param taContact 实体对象
     * @return
     */
    @RequestMapping(value = "/channel/taContact", method = RequestMethod.POST)
    public ResponseBean taContactAdd(@RequestBody TaContact taContact) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taContact.setCreateDate(LocalDateTime.now());
            taContact.setStatus(CommConstant.STATUS_NORMAL);
            if (iTaContactService.save(taContact)) {
                responseBean.addSuccess(taContact);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "/channel/taContact/batchDelete", method = RequestMethod.PUT)
    public ResponseBean batchDelete(@RequestBody List<TaContact> taContactList, HttpServletRequest request) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean = iTaContactService.batchDelete(taContactList, getSysUserId(request));
            logger.info("TaContactController.batchDelete 返回结果：", JSONObject.toJSONString(responseBean));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     *
     * @param id        实体ID
     * @param taContact 实体对象
     * @return
     */
    @RequestMapping(value = "/channel/taContact/{id}", method = RequestMethod.PUT)
    public ResponseBean taContactUpdate(@PathVariable Integer id,
                                        @RequestBody TaContact taContact) {
        ResponseBean responseBean = new ResponseBean();
        TaContact contact = iTaContactService.getById(id);
        if (!StringUtils.isEmpty(contact.getContactType())){
            taContact.setContactType(contact.getContactType());
        }
        try {
            if (iTaContactService.updateById(taContact)) {
                responseBean.addSuccess(taContact);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactUpdate -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

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

    /**
     * 联系人列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/channel/taContact", method = RequestMethod.GET)
    public ResponseBean getContactList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                       @RequestParam(value = "contactName", required = false) String contactName,
                                       @RequestParam(value = "telephone", required = false) String telephone,
                                       @RequestParam(value = "phone", required = false) String phone,
                                       @RequestParam(value = "job", required = false) String job) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaContact> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaContact> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(contactName), "contact_name", contactName);
            queryWrapper.like(!StringUtils.isEmpty(telephone), "telephone", telephone);
            queryWrapper.like(!StringUtils.isEmpty(phone), "phone", phone);
            queryWrapper.like(!StringUtils.isEmpty(job), "job", job);
            queryWrapper.eq("status", CommConstant.STATUS_NORMAL);
            queryWrapper.orderByDesc("order_no", "create_date");

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

    /**
     * 根据样例id查询联系人信息
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/admin/taContact/{id}", method = RequestMethod.GET)
    public ResponseBean taContactInfoBySampleId(@PathVariable String id,
                                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(iTaContactService.taContactInfoBySampleId(id, pageNum, pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactDelete -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 条件查询联系人列表
     *
     * @param pageNum
     * @param pageSize
     * @param contactName
     * @param telephone
     * @param phone
     * @param job
     * @return
     */
    @RequestMapping(value = "/admin/listContactByCondition", method = RequestMethod.GET)
    public ResponseBean listContactByConditionForAdmin(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                       String contactName, String telephone, String phone, String job) {
        ResponseBean responseBean = new ResponseBean();
        try {
            //使用分页插件
            IPage<TaContact> pg = new Page<>(pageNum, pageSize);
            QueryWrapper<TaContact> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(!StringUtils.isEmpty(contactName), "contact_name", contactName);
            queryWrapper.like(!StringUtils.isEmpty(telephone), "telephone", telephone);
            queryWrapper.like(!StringUtils.isEmpty(phone), "phone", phone);
            queryWrapper.like(!StringUtils.isEmpty(job), "job", job);
            queryWrapper.like("contact_type", CommConstant.CONTACT_FINANCE);
            queryWrapper.ne("status", CommConstant.STATUS_DELETE);
            queryWrapper.orderByDesc("order_no", "create_date");

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

    /**
     * 新增财务联系人
     *
     * @param id 实体ID
     */
    @RequestMapping(value = "/channel/taContactFinance/{id}", method = RequestMethod.PUT)
    public ResponseBean taContactInfoAdd(@PathVariable Integer id) {
        ResponseBean responseBean = new ResponseBean();
        TaContact contact = iTaContactService.getById(id);
        try {
            TaContact taContact = new TaContact();
            taContact.setContactId(id);
            taContact.setContactType(CommConstant.CONTACT_FINANCE);
            if (!StringUtils.isEmpty(contact.getOrderNo())){
                taContact.setOrderNo(contact.getOrderNo());
            }
            if (iTaContactService.updateById(taContact)) {
                responseBean.addSuccess(taContact);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactInfoAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 删除财务联系人
     */
    @RequestMapping(value = "/channel/taContactFinanceDel", method = RequestMethod.PUT)
    public ResponseBean taContactInfoAdd(@RequestBody List<TaContact> taContacts) {
        ResponseBean responseBean = new ResponseBean();
        try {
            taContacts.forEach(e -> {
                e.setContactType(e.getContactType().replaceAll( "finance,|,finance|finance",""));
            });
            if (iTaContactService.updateBatchById(taContacts)) {
                responseBean.addSuccess(taContacts);
            } else {
                responseBean.addError("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("taContactInfoAdd -=- {}", e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }
}
