package com.dcsoft.system.vehicle.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.core.utils.poi.ExcelUtil;
import com.dcsoft.common.core.web.controller.BaseController;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.core.web.page.TableDataInfo;
import com.dcsoft.common.log.annotation.Log;
import com.dcsoft.common.log.enums.BusinessType;
import com.dcsoft.common.security.annotation.RequiresPermissions;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.vehicle.domain.CarInfo;
import com.dcsoft.system.vehicle.domain.CarPark;
import com.dcsoft.system.vehicle.domain.CarParkItem;
import com.dcsoft.system.vehicle.domain.CarParkRecord;
import com.dcsoft.system.vehicle.service.ICarInfoService;
import com.dcsoft.system.vehicle.service.ICarParkItemService;
import com.dcsoft.system.vehicle.service.ICarParkRecordService;
import com.dcsoft.system.vehicle.service.ICarParkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 车辆信息Controller
 *
 * @author nichun
 * @date 2023-12-26
 */
@RestController
@RequestMapping("/carInfo")
public class CarInfoController extends BaseController
{
    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private ICarParkRecordService carParkRecordService;

    @Autowired
    private ICarParkItemService carParkItemService;

    @Autowired
    private ICarParkService carParkService;

    /**
     * 查询车辆信息列表
     */
    @RequiresPermissions("system:carInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(CarInfo carInfo) {
        startPage();
        if (StrUtil.isBlank(carInfo.getDelFlag())) {
            carInfo.setDelFlag("0");
        }
        List<CarInfo> list = carInfoService.selectCarInfoList(carInfo);
        return getDataTable(list);
    }

    /**
     * 导出车辆信息列表
     */
    @RequiresPermissions("system:carInfo:export")
    @Log(title = "车辆信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CarInfo carInfo) {
        if (StrUtil.isBlank(carInfo.getDelFlag())) {
            carInfo.setDelFlag("0");
        }
        List<CarInfo> list = carInfoService.selectCarInfoList(carInfo);
        ExcelUtil<CarInfo> util = new ExcelUtil<CarInfo>(CarInfo.class);
        util.exportExcel(response, list, "车辆信息数据");
    }

    @Log(title = "车辆信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:carInfo:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<CarInfo> util = new ExcelUtil<CarInfo>(CarInfo.class);
        List<CarInfo> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = carInfoService.importData(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<CarInfo> util = new ExcelUtil<CarInfo>(CarInfo.class);
        util.importTemplateExcel(response, "出勤调整数据");
    }


    /**
     * 获取车辆信息详细信息
     */
    @RequiresPermissions("system:carInfo:query")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId)
    {
        return success(carInfoService.selectCarInfoByCustomerId(customerId));
    }

    /**
     * 新增车辆信息
     */
    @RequiresPermissions("system:carInfo:add")
    @Log(title = "车辆信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CarInfo carInfo) {
        if (!StrUtil.equals("2", carInfo.getCarType()) && !checkPlateNumberFormat(carInfo.getPlate())) {
            return AjaxResult.error("车牌号不正确！");
        }
        CarInfo car = carInfoService.selectCarInfoByPlate(carInfo.getPlate());
        if (ObjectUtil.isNotEmpty(car)) {
            return AjaxResult.error("车牌号已存在，不可重复添加！");
        }

        int i = carInfoService.insertCarInfo(carInfo);
        //保存车辆授权
        //根据车场查询车辆
        if (carInfo.getParkId() != null) {
            List<Long> list = new ArrayList<>();
            CarPark park = carParkService.selectCarParkById(carInfo.getParkId());
            list.add(carInfo.getParkId());
            list.add(park.getParentId());

            CarParkItem carParkItem = new CarParkItem();
            carParkItem.setParkIds(list);
            List<CarParkItem> itemList = carParkItemService.selectCarParkItemList(carParkItem);
            for (CarParkItem a : itemList) {
                CarParkRecord carParkRecord = new CarParkRecord();
                carParkRecord.setCustomerId(carInfo.getCustomerId());
                carParkRecord.setParkId(a.getParkId());
                carParkRecord.setEquipmentId(a.getEquipmentId());
                carParkRecordService.insertCarParkRecord(carParkRecord);
            }
        }
        return toAjax(i);
    }

    /**
     * 修改车辆信息
     */
    @RequiresPermissions("system:carInfo:edit")
    @Log(title = "车辆信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CarInfo carInfo) {
        if (!StrUtil.equals("2", carInfo.getCarType()) && !checkPlateNumberFormat(carInfo.getPlate())) {
            return AjaxResult.error("车牌号不正确！");
        }
        if (StringUtils.equals("1", carInfo.getTimeSegEnable()) && StringUtils.isBlank(carInfo.getSegTime())) {
            return AjaxResult.error("已启用时间段，时间段不能为空！");
        }

        //根据车场查询车辆
        if (carInfo.getParkId() != null) {
            //删除车辆授权
            carParkRecordService.deleteCarParkRecordByCustomerId(carInfo.getCustomerId());

            List<Long> list = new ArrayList<>();
            CarPark park = carParkService.selectCarParkById(carInfo.getParkId());
            list.add(carInfo.getParkId());
            list.add(park.getParentId());
            CarParkItem carParkItem = new CarParkItem();
            carParkItem.setParkIds(list);
            List<CarParkItem> itemList = carParkItemService.selectCarParkItemList(carParkItem);
            for (CarParkItem a : itemList) {
                CarParkRecord carParkRecord = new CarParkRecord();
                carParkRecord.setCustomerId(carInfo.getCustomerId());
                carParkRecord.setParkId(a.getParkId());
                carParkRecord.setEquipmentId(a.getEquipmentId());
                carParkRecordService.insertCarParkRecord(carParkRecord);

            }
        }
        return toAjax(carInfoService.updateCarInfo(carInfo));
    }

    /**
     * 删除车辆信息
     */
    @RequiresPermissions("system:carInfo:remove")
    @Log(title = "车辆信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(carInfoService.deleteCarInfoByCustomerIds(customerIds));
    }

    /**
     * 还原删除车辆信息
     */
    @RequiresPermissions("system:delCarInfo:restore")
    @Log(title = "车辆还原", businessType = BusinessType.UPDATE)
    @PostMapping("/restore")
    public AjaxResult restore(@RequestBody List<Long> customerIds) {
        return toAjax(carInfoService.restore(customerIds));
    }

    /**
     * 获取企业模块|菜单权限树
     */
    @GetMapping(value = "/tree")
    public AjaxResult tree() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("depts", carInfoService.selectTree());
        return ajax;
    }

    /**
     * 获取企业模块|菜单权限树
     */
    @GetMapping(value = "/carPlay/{id}")
    public AjaxResult carPlay(@PathVariable("id") Long id) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("plays", carInfoService.carPlay(id));
        return ajax;
    }

    /**
     * 获取企业模块|菜单权限树
     */
    @GetMapping(value = "/carPlayRecord/{id}")
    public AjaxResult carPlayRecord(@PathVariable("id") Long id) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("records", carInfoService.carPlayRecord(id));
        return ajax;
    }

    /**
     * 获取企业模块|菜单权限树
     */
    @GetMapping(value = "/selectCarInfo/{id}/{flag}")
    public AjaxResult selectCarInfo(@PathVariable("id") Long id,@PathVariable("flag") String flag) {
        return toAjax(carInfoService.selectCarInfo(id,flag));
    }

    public boolean checkPlateNumberFormat(String content) {
        String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([ADF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[ADF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(pattern, content);
    }

}
