package com.sysu.admin.support.system.organ;

import com.google.common.base.Objects;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.sysu.admin.support.base.BaseVo;
import com.sysu.admin.support.base.ServiceContext;
import com.xiesx.fastboot.base.pagination.PaginationHelper;
import com.xiesx.fastboot.base.pagination.PaginationResult;
import com.xiesx.fastboot.base.pagination.PaginationVo;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.core.exception.RunException;
import com.xiesx.fastboot.utils.CopyUtils;
import com.sysu.admin.support.system.user.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @title OrganController
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:04:18
 */
@Controller
@RequestMapping("/organ")
public class OrganController extends ServiceContext {

    /**
     * 页面
     *
     * @return
     */
    @RequestMapping(value = "index")
    @RequiresPermissions("organ:select")
    public String index(Model model) {
        return "system/organ/index";
    }

    /**
     * 分页
     *
     * @param base
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "page")
    @RequiresPermissions("organ:select")
    public PaginationResult page(BaseVo base, PaginationVo page) {
        // 对象
        QOrgan qOrgan = QOrgan.organ;
        // 条件
        Predicate predicate = qOrgan.id.isNotNull();
        if (ObjectUtils.isNotEmpty(base.getKeyword())) {
            Predicate p1 = qOrgan.id.like("%" + base.getKeyword() + "%");
            Predicate p2 = qOrgan.company.likeIgnoreCase("%" + base.getKeyword() + "%");
            Predicate p3 = qOrgan.contacts.likeIgnoreCase("%" + base.getKeyword() + "%");

            predicate = ExpressionUtils.and(predicate, ExpressionUtils.anyOf(p1, p2, p3));
        }

        User currentUser = mShiroService.getCurrentUser();

        //县级执法权限可以看下级的部门
        if(mShiroService.isXjzf()){
            predicate = ExpressionUtils.and(predicate, qOrgan.parentId.eq(currentUser.getOrganId()));
        }


        // 排序
        Sort sort = Sort.by(Direction.DESC, Organ.FIELDS.id);
        // 分页
        Pageable pageable = PageRequest.of(page.getPage(), page.getLimit(), sort);
        // 查询数据
        Page<Organ> data = mOrganService.findAll(predicate, pageable);
        // 构造
        return PaginationHelper.create(data);
    }


    /**
     * 中心选择器数据
     * @param base
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "centerSelect")
    public PaginationResult centerSelect(BaseVo base, PaginationVo page){
        // 对象
        QOrgan qOrgan = QOrgan.organ;
        // 条件
        Predicate predicate = qOrgan.id.isNotNull();
        if (ObjectUtils.isNotEmpty(base.getKeyword())) {
            Predicate p1 = qOrgan.id.like("%" + base.getKeyword() + "%");
            Predicate p2 = qOrgan.company.likeIgnoreCase("%" + base.getKeyword() + "%");
            Predicate p3 = qOrgan.contacts.likeIgnoreCase("%" + base.getKeyword() + "%");
            predicate = ExpressionUtils.and(predicate, ExpressionUtils.anyOf(p1, p2, p3));
        }

        //县级执法权限可以看下级的部门
        if(mShiroService.isXjzf()){
            User currentUser = mShiroService.getCurrentUser();
            predicate = ExpressionUtils.and(predicate, qOrgan.parentId.eq(currentUser.getOrganId()));
        }

        if(ObjectUtils.isNotEmpty(base.getCityName())){
            predicate = ExpressionUtils.and(predicate, qOrgan.cityName.like(base.getCityName() + "%"));
        }

        predicate = ExpressionUtils.and(predicate, qOrgan.isBureau.eq(base.getIsBureau()));


        // 排序
        Sort sort = Sort.by(Direction.DESC, Organ.FIELDS.updateDate);
        // 分页
        Pageable pageable = PageRequest.of(page.getPage(), page.getLimit(), sort);
        // 查询数据
        Page<Organ> data = mOrganService.findAll(predicate, pageable);
        // 构造
        return PaginationHelper.create(data);

    }

    /**
     * 详情
     *
     * @param base
     * @param model
     * @return
     * @throws RunException
     */
    @RequestMapping(value = "form")
    @RequiresPermissions("organ:select")
    public String form(BaseVo base, Model model) {
        Organ organ = new Organ().setId(base.getId());
        if (!Objects.equal(organ.getId(), -1L)) {
            organ = mOrganService.findOne(organ.getId());
        }
        model.addAttribute("organ", organ);
        model.addAttribute("json", organ.toJSONString());
        return "system/organ/form";
    }

    /**
     * 更新,添加
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submit")
    @RequiresPermissions("organ:update")
    public BaseResult submit(BaseVo base, Organ req) {
        Organ organ = new Organ().setId(req.getId());
        if (Objects.equal(organ.getId(), -1L)) {
            BeanUtils.copyProperties(req, organ);
        } else {
            organ = mOrganService.findOne(base.getId());
            BeanUtils.copyProperties(req, organ, CopyUtils.ignoreNullNames(req));
        }

        // 区县
        if (ObjectUtils.isNotEmpty(req.getCityName())) {
            organ.setCityName(req.getCityName());
        } else {
            organ.setCityName(null);
        }

        // 先保存
        organ = mOrganService.saveAndFlush(organ);
        Integer row = mOrganService.insertOrUpdate(organ);
        return (row >= 1) ? R.succ() : R.fail();
    }

    @ResponseBody
    @RequestMapping(value = "batchTestUser")
    public BaseResult batchTestUser(Integer isBureau){
        mOrganService.batchTestUser(isBureau);
        return R.succ();
    }

    /**
     * 删除
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @RequiresPermissions("organ:delete")
    public BaseResult delete(BaseVo base) {
        Integer row = mOrganService.delete(base.getIds());
        return (row >= 1) ? R.succ() : R.fail();
    }
}
