package com.crm.web.controller;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.dto.web.information.WebInformationSearchDto;
import com.crm.rely.backend.model.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.model.entity.web.information.WebInformationAddEntity;
import com.crm.rely.backend.model.entity.web.information.WebInformationDeleteEntity;
import com.crm.rely.backend.model.entity.web.information.WebInformationSearchListEntity;
import com.crm.rely.backend.model.entity.web.information.WebInformationUpdateEntity;
import com.crm.rely.backend.service.RedisService;
import com.crm.web.service.CommonService;
import com.crm.web.service.WebInformationService;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: houn
 */
@RestController
@RequestMapping("/information")
public class WebInformationController {

    @Autowired
    private WebInformationService webInformationService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CommonService commonService;

    @PostMapping("/custom/list")
    public ResultWithPagerDto<WebInformationSearchDto> getResultWebInformationSearchList(@Validated @RequestBody WebInformationSearchListEntity entity) throws ServiceException {
        entity.setValid(1);
        entity.setTime(new Date());
        validSortName(entity.getSortName());
        ResultWithPagerDto<WebInformationSearchDto> result = webInformationService.pageSearchList(entity);
        if (result.getData() != null && result.getData().size() > 0) {
            result.getData().forEach(v -> {
                v.setContent(null);
            });
        }
        return result;
    }

    @PostMapping("/custom/single")
    public BaseResultDto<WebInformationSearchDto> customSingle(@RequestBody @Validated SingleLongEntity entity) throws Exception {

        BaseResultDto<WebInformationSearchDto> result = webInformationService.searchSingle(entity.getId());

        return result;
    }

    /**
     * 添加信息
     *
     * @param entity
     * @param infoEntity
     * @return
     * @throws Exception
     */
    @PostMapping("/manager/add")
    public BaseResultDto add(@RequestBody @Validated WebInformationAddEntity entity, UserInfoEntity infoEntity,
                             HttpServletRequest httpServletRequest) throws Exception {

        Runnable runnable = () -> {
            if (entity.getValid() == null) {
                entity.setValid(0);
            }

            if (entity.getTopping() == null) {
                entity.setTopping(0);
            }
            webInformationService.add(entity);
        };
        redisService.tryLock(infoEntity, httpServletRequest, runnable, "no_repeat_submit_error");

        return BaseResultDto.success();

    }

    /**
     * 删除信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/manager/delete")
    public BaseResultDto delete(@RequestBody @Validated WebInformationDeleteEntity entity, UserInfoEntity infoEntity) throws Exception {

        webInformationService.delete(entity);
        return BaseResultDto.success();
    }

    /**
     * 修改信息
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/manager/update")
    public BaseResultDto update(@RequestBody @Validated WebInformationUpdateEntity entity, UserInfoEntity infoEntity) throws Exception {

        if (entity.getValid() == null) {
            entity.setValid(0);
        }
        if (entity.getTopping() == null) {
            entity.setTopping(0);
        }
        webInformationService.update(entity);
        return BaseResultDto.success();
    }

    /**
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/manager/search/list")
    public ResultWithPagerDto<WebInformationSearchDto> pageSearchList(@RequestBody @Validated WebInformationSearchListEntity entity, UserInfoEntity infoEntity) throws Exception {
        validSortName(entity.getSortName());
        ResultWithPagerDto<WebInformationSearchDto> result = webInformationService.pageSearchList(entity);

        return result;
    }

    @PostMapping("/manager/search/single")
    public BaseResultDto<WebInformationSearchDto> single(@RequestBody @Validated SingleLongEntity entity, UserInfoEntity infoEntity) throws Exception {

        BaseResultDto<WebInformationSearchDto> result = webInformationService.searchSingle(entity.getId());

        return result;
    }


    @PostMapping("/manager/upload")
    public BaseResultDto upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        String middlePath = "/information";
        commonService.validated(file);
        String path = commonService.uploadFile(middlePath, file);
        return BaseResultDto.success(Constants.UPLOAD_SUCCESS, path);
    }

    private void validSortName(String sortName) {
        if (!Strings.isNullOrEmpty(sortName)) {
            List<String> tableFields = new ArrayList<>(10);
            tableFields.add("id");
            tableFields.add("add_time");
            tableFields.add("modify_time");
            if (!tableFields.contains(sortName)) {
                throw ServiceException.exception(Constants.FAIL);
            }
        }
    }
}
