package com.cwhelp.admin.business.controller;

import com.cwhelp.admin.business.validator.BssEnterpriseValid;
import com.cwhelp.common.constant.PlatformConst;
import com.cwhelp.common.enums.ResultEnum;
import com.cwhelp.common.enums.StatusEnum;
import com.cwhelp.common.utils.EntityBeanUtil;
import com.cwhelp.common.utils.ResultVoUtil;
import com.cwhelp.common.utils.StatusUtil;
import com.cwhelp.common.vo.ResultVo;
import com.cwhelp.component.shiro.ShiroUtil;
import com.cwhelp.modules.business.domain.BssEnterprise;
import com.cwhelp.modules.business.domain.BssPlatform;
import com.cwhelp.modules.business.service.BssEnterpriseService;
import com.cwhelp.modules.system.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yan.y
 * @date 2019/08/06
 */
@Controller
@RequestMapping("/bss/enterprise")
public class BssEnterpriseController {

    @Autowired
    private BssEnterpriseService bssEnterpriseService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("bss:enterprise:index")
    public String index(Model model, BssEnterprise bssEnterprise) {
        User user = ShiroUtil.getSubject();

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", match -> match.contains())
                .withMatcher("platform.id",match -> match.contains());
        BssPlatform bssPlatform = new BssPlatform();
        bssPlatform.setId(user.getBssPlatform().getId());
        bssEnterprise.setPlatform(bssPlatform);

        // 获取数据列表
        Example<BssEnterprise> example = Example.of(bssEnterprise, matcher);
        Page<BssEnterprise> list = bssEnterpriseService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/business/enterprise/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("bss:enterprise:add")
    public String toAdd(Model model) {
        User user = ShiroUtil.getSubject();
        BssPlatform bssPlatform = user.getBssPlatform();
        model.addAttribute("bssPlatform",bssPlatform);
        return "/business/enterprise/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("bss:enterprise:edit")
    public String toEdit(@PathVariable("id") BssEnterprise bssEnterprise, Model model) {
        User user = ShiroUtil.getSubject();
        BssPlatform bssPlatform = user.getBssPlatform();
        model.addAttribute("bssPlatform",bssPlatform);
        model.addAttribute("bssEnterprise", bssEnterprise);
        return "/business/enterprise/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping({"/add","/edit"})
    @RequiresPermissions({"bss:enterprise:add","bss:enterprise:edit"})
    @ResponseBody
    public ResultVo save(@Validated BssEnterpriseValid valid, BssEnterprise bssEnterprise) {
        // 复制保留无需修改的数据
        if (bssEnterprise.getId() != null) {
            BssEnterprise beEnterprise = bssEnterpriseService.getById(bssEnterprise.getId());
            EntityBeanUtil.copyProperties(beEnterprise, bssEnterprise);
        }

        User user = ShiroUtil.getSubject();
        BssPlatform bssPlatform = user.getBssPlatform();
        int platformType = bssPlatform.getType();

        if (platformType == PlatformConst.COMPANY_TYPE) {
            List<BssEnterprise> listByPlatform = bssEnterpriseService.getListByPlatform(bssPlatform);
            if (listByPlatform.size() > 1) {
                return ResultVoUtil.error(ResultEnum.ENTERPRISE_NUMBER_EXCESSIVE.getCode(),ResultEnum.ENTERPRISE_NUMBER_EXCESSIVE.getMessage());
            }
        }

        if (bssEnterpriseService.repeatByName(bssEnterprise)) {
            return ResultVoUtil.error(ResultEnum.ENTERPRISE_NAME_EXIST.getCode(),ResultEnum.ENTERPRISE_NAME_EXIST.getMessage());
        }

        if (bssEnterpriseService.repeatByCreditCode(bssEnterprise)) {
            return ResultVoUtil.error(ResultEnum.ENTERPRISE_CREDITCODE_EXIST.getCode(),ResultEnum.ENTERPRISE_CREDITCODE_EXIST.getMessage());
        }

        // 保存数据
        bssEnterpriseService.save(bssEnterprise);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("bss:enterprise:detail")
    public String toDetail(@PathVariable("id") BssEnterprise bssEnterprise, Model model) {
        model.addAttribute("bssEnterprise",bssEnterprise);
        return "/business/enterprise/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("bss:enterprise:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (bssEnterpriseService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}