package com.willalp.web.controller.code;

import com.willalp.code.domain.HsSysCode;
import com.willalp.code.service.IHsSysCodeService;
import com.willalp.common.annotation.Log;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.domain.entity.HsSysLevels;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.BusinessType;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 编码配置Controller
 *
 * @author bjh
 * @date 2021-12-06
 */
@RestController
@RequestMapping("/code/rule")
public class HsSysCodeController extends BaseController
{
    @Autowired
    private IHsSysCodeService hsSysCodeService;

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(HsSysLevels level)
    {
        List<HsSysLevels> levels = hsSysCodeService.selectLevelList(level);
        return AjaxResult.success(hsSysCodeService.buildLevelTreeSelect(levels));
    }

    @PreAuthorize("@ss.hasPermi('code:rule:list')")
    @GetMapping("/list")
    public TableDataInfo list(HsSysCode code)
    {
        startPage();
        //user.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        List<HsSysCode> list = hsSysCodeService.selectCodeList(code);
        return getDataTable(list);
    }

    /**
     * 获取层级规则详细信息
     */
    @PreAuthorize("@ss.hasPermi('code:rule:query')")
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id") String id)
    {

        return AjaxResult.success(hsSysCodeService.selectCodeById(Long.valueOf(id)));
    }

    /**
     * 查询编码配置列表
     */
/*    @PreAuthorize("@ss.hasPermi('code:rule:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request) throws IOException {
        //加入条件
        QueryWrapper<TreeAndTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        String name = request.getParameter("name");
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.eq("name", name);
        }
        String type = request.getParameter("type");
        if (!StringUtils.isEmpty(type)) {
            queryWrapper.eq("type", type);
        }
        String areaId = request.getParameter("areaId");
        if (!StringUtils.isEmpty(areaId)) {
            queryWrapper.eq("area_id", areaId);
        }
        // 预处理
        Page pageBean = hsSysCodeService.page(getPage(), queryWrapper);
        return getDataTable(pageBean);
    }*/

    /**
     * 导出编码配置列表
     */
    @PreAuthorize("@ss.hasPermi('code:rule:export')")
    @Log(title = "编码配置", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HsSysCode hsSysCode)
    {
        List<HsSysCode> list = hsSysCodeService.selectCodeList(hsSysCode);
        ExcelUtil<HsSysCode> util = new ExcelUtil<HsSysCode>(HsSysCode.class);
        return util.exportExcel(list, "编码配置数据");
    }



    /**
     * 新增编码配置
     */
    @PreAuthorize("@ss.hasPermi('code:rule:add')")
    @Log(title = "编码配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsSysCode hsSysCode)
    {
        Long id = hsSysCodeService.getByMaxId();
        Long mark = hsSysCodeService.getIsParentid(hsSysCode.getLevelid());
        if(mark>0){
            return AjaxResult.error(" 新增失败，该层级有子节点");
        }
        hsSysCode.setId(id);
        hsSysCode.setSfzx("0");
        hsSysCode.setCreateBy(SecurityUtils.getUsername());
        hsSysCode.setCreateTime(DateUtils.getNowDate());
        int parentid = 1;
        String shcode ="";
        String levelid = hsSysCode.getLevelid();
        while( parentid!=0){
            HsSysLevels syslevel = hsSysCodeService.selectHsSysLevelList(hsSysCode); //层级信息
            if(syslevel!=null){
                shcode = syslevel.getLevelcode() + shcode;
            }
            parentid = syslevel.getParentId()==null?0: Integer.valueOf(syslevel.getParentId()+"");
            hsSysCode.setLevelid(parentid+"");
        }
        hsSysCode.setRemark(shcode);
        hsSysCode.setLevelid(levelid);
        return toAjax(hsSysCodeService.insertCode(hsSysCode));
    }

    /*
     * 修改编码配置
     */
    @PreAuthorize("@ss.hasPermi('code:rule:edit')")
    @Log(title = "编码配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsSysCode hsSysCode)
    {
        List<Map<String,Object>> data = hsSysCodeService.checkCodeApply(Long.parseLong(hsSysCode.getId()));
        if(data.size()>0){
            return AjaxResult.error("修改失败，该编码已有申请"  );
        }
        hsSysCode.setUpdateBy(SecurityUtils.getUsername());
        hsSysCode.setUpdateTime(DateUtils.getNowDate());
        return toAjax(hsSysCodeService.updateCode(hsSysCode));
    }

    /**
     * 删除编码配置
     */
    @PreAuthorize("@ss.hasPermi('code:rule:remove')")
    @Log(title = "编码配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long[] id)
    {
        List<Map<String,Object>> data = hsSysCodeService.checkCodeApply(id[0]);
        if(data.size()>0){
            return AjaxResult.error("删除失败，已有编码申请"  );
        }
        return toAjax(hsSysCodeService.removeByIds(id));
    }


    @PreAuthorize("@ss.hasPermi('code:rule:listofall')")
    @GetMapping("/listofall")
    public TableDataInfo listofall(HsSysCode code)
    {
        startPage();
        List<HsSysCode> list = hsSysCodeService.selectCodeListOfAll(code);
        List<HsSysLevels> lists = new ArrayList<HsSysLevels>();

        for(HsSysCode sc:list){
            String b = sc.getName1();
            HsSysLevels sl = hsSysCodeService.selectHsSysLevelList(sc); //层级信息
            b = sl.getLevelcode()+ b;
            long parentid = sl.getParentId();
            while(parentid!=0 ){
                HsSysLevels level = hsSysCodeService.getLevelcode(parentid);
                b = level.getLevelcode()+b;
                parentid = level.getParentId()+0;
            }
            sl.setLevelcode(b);
            sl.setSummary(sc.getSummary());
            sl.setXh(sc.getId()+"");
            lists.add(sl);
        }
        return getDataTable(lists);
    }
}
