package com.fs.hisStore.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.hisStore.domain.ForbiddenOnlineMedicine;
import com.fs.hisStore.facade.FsStore580FacadeService;
import com.fs.hisStore.utils.StoreAuditLogUtil;
import com.fs.hisStore.vo.*;
import com.fs.hospital580.service.Hospital580ScrmService;
import com.fs.statis.dto.ModifyMoreDTO;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.domain.FsStoreProductAttrScrm;
import com.fs.hisStore.param.FsProductAttrValueParam;
import com.fs.hisStore.param.FsStoreProductAddEditParam;
import com.fs.hisStore.param.FsStoreTuiProductAttrValueParam;
import com.fs.hisStore.service.IFsStoreProductAttrScrmService;
import com.fs.hisStore.service.IFsStoreProductAttrValueScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.statis.dto.ProductAuditDTO;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 商品Controller
 *
 * @author fs
 * @date 2022-03-15
 */
@Slf4j
@RestController
@RequestMapping("/store/store/storeProduct")
public class FsStoreProductScrmController extends BaseController {

    @Autowired
    private IFsStoreProductScrmService fsStoreProductService;

    @Autowired
    private IFsStoreProductAttrScrmService attrService;

    @Autowired
    private IFsStoreProductAttrValueScrmService attrValueService;

    @Autowired
    private Hospital580ScrmService fsStoreHospital580ScrmService;

    @Autowired
    private FsStore580FacadeService fsStore580FacadeService;

    @Autowired
    private StoreAuditLogUtil storeAuditLogUtil;

    /**
     * 商品关键字检查
     * 只要商品成分的关键字在数据库中存在，就不允许添加商品。
     * @param keyWords
     * @return
     */
    @Log(title = "商品管理", businessType = BusinessType.AUDIT, isStoreLog = true, logParam = {"商品", "商品关键字检查"})
    @GetMapping("/selectForbiddenKeywords/{keyWords}")
    public R selectForbiddenKeywords(@PathVariable("keyWords")String keyWords) {
        if(org.apache.commons.lang3.StringUtils.isEmpty(keyWords))return R.ok().put("data", true);
        List<ForbiddenOnlineMedicine> list = fsStoreProductService.selectForbiddenKeywords(keyWords);
        if(CollectionUtils.isEmpty(list)){
            return R.ok().put("data", true);
        }else{
            return R.ok().put("data", false).put("msg", list.get(0).getModule());
        }
    }

    /**
     * 判断该药店的经营许可证是否允许上架该商品
     * @param fsStoreProduct
     */
    @PostMapping("/checkStoreDrugLicense")
    public R checkStoreDrugLicense(@RequestBody FsStoreProductAddEditParam fsStoreProduct) {
        return R.ok().put("data", fsStoreProductService.checkStoreDrugLicense(fsStoreProduct.getStoreId(), fsStoreProduct.getCateId(),
                org.apache.commons.lang3.StringUtils.isEmpty(fsStoreProduct.getMedicalDeviceCode())?null:fsStoreProduct.getMedicalDeviceCode()));
    }

    /**
     * 批量修改商品
     *
     * @param modifyMoreDTO
     * @return
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:list')")
    @PostMapping("/batchModify")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE, isStoreLog = true, logParam = {"商品", "批量修改商品信息"})
    public R batchModify(@RequestBody ModifyMoreDTO modifyMoreDTO) {
        fsStoreProductService.batchModify(modifyMoreDTO);
        return R.ok();
    }

    @PreAuthorize("@ss.hasPermi('store:storeProduct:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT, businessTypeExpression = "#p0.getProductId()>0? T(com.fs.common.enums.BusinessType).UPDATE: T(com.fs.common.enums.BusinessType).INSERT"
            , isStoreLog = true, logParamExpression = "#p0.getProductId()>0? new String[]{'商品','修改商品'}: new String[]{'商品','新增商品'}")
    @PostMapping(value = "/addOrEdit")
    public R addOrEdit(@RequestBody FsStoreProductAddEditParam fsStoreProduct) {
        if (ObjectUtils.isNotNull(fsStoreProduct.getIsShow())) {
            if (fsStoreProduct.getIsShow() == 1) {
                logger.info("商品上架：{}", fsStoreProduct.getProductName() + new Date());
            }
        }

        if (ObjectUtils.isNotNull(fsStoreProduct.getIsDisplay())) {
            if (fsStoreProduct.getIsDisplay() == 1) {
                logger.info("商品前端展示：{}", fsStoreProduct.getProductName() + new Date());
            }
        }
        return fsStoreProductService.addOrEdit(fsStoreProduct);
    }

    @PreAuthorize("@ss.hasPermi('store:storeProduct:list')")
    @PostMapping("/batchAudit")
    @Log(title = "商品审核", businessType = BusinessType.AUDIT, isStoreLog = true, logParam = {"商品", "批量审核商品信息"},
            logParamExpression = "#p0.getProductIds().size()>1?"
                    + "(#p0.isAudit==1?new String[]{'商品','商品批量审核通过'}: new String[]{'商品','商品批量审核退回'}):" +
                    "(#p0.isAudit==1?new String[]{'商品','商品审核通过'}: new String[]{'商品','商品审核退回'})")
    public R batchAudit(@RequestBody ProductAuditDTO auditDTO) {
        fsStoreProductService.batchAudit(auditDTO);
        return R.ok();
    }

    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsStoreProductScrm fsStoreProduct) {
        log.info("查询商品列表 参数: {}", fsStoreProduct);
        startPage();
        List<FsStoreProductListVO> list;
        if (StringUtils.isNullOrEmpty(fsStoreProduct.getBarCode())) {
            list = fsStoreProductService.selectFsStoreProductListVO(fsStoreProduct);
        } else {
            list = fsStoreProductService.selectFsStoreProductBarCodeListVO(fsStoreProduct);
        }
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:export')")
    @Log(title = "商品管理", businessType = BusinessType.EXPORT, isStoreLog = true, logParam = {"商品", "导出商品信息"})
    @GetMapping("/export")
    public AjaxResult export(FsStoreProductScrm fsStoreProduct) {
        List<FsStoreProductExportVO> list = fsStoreProductService.selectFsStoreProductExportList(fsStoreProduct);
        ExcelUtil<FsStoreProductExportVO> util = new ExcelUtil<FsStoreProductExportVO>(FsStoreProductExportVO.class);
        return util.exportExcel(list, "storeProduct");
    }

    /**
     * 导出
     * @param fsStoreProduct
     * @return
     */
    @Log(title = "药品首营品种登记表管理", businessType = BusinessType.EXPORT, isStoreLog = true, logParam = {"药品首营品种", "导出药品首营品种登记表"})
    @GetMapping("/exportProduct")
    public  AjaxResult exportProduct(FsStoreProductScrm fsStoreProduct) {
        List<FsDrugExportVO> fsDrugExportVOS = fsStoreProductService.selectFsDrugExportList(fsStoreProduct);
        ExcelUtil<FsDrugExportVO> util = new ExcelUtil<FsDrugExportVO>(FsDrugExportVO.class);
        return util.exportExcel(fsDrugExportVOS, "药品首营品种登记表");
    }


    @Log(title = "商品管理", businessType = BusinessType.IMPORT, isStoreLog = true, logParam = {"商品", "商品导入"})
    @PreAuthorize("@ss.hasPermi('store:storeProduct:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<FsStoreProductExportVO> util = new ExcelUtil<>(FsStoreProductExportVO.class);
        List<FsStoreProductExportVO> list = util.importExcel(file.getInputStream());
        String message = fsStoreProductService.importStoreProduct(list, updateSupport);
        return AjaxResult.success(message);
    }


    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<FsStoreProductExportVO> util = new ExcelUtil<>(FsStoreProductExportVO.class);
        return util.importTemplateExcel("商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:query')")
    @GetMapping(value = "/{productId}")
    public R getInfo(@PathVariable("productId") Long productId) {
        FsStoreProductScrm product = fsStoreProductService.selectFsStoreProductById(productId);
        List<FsStoreProductAttrScrm> attrs = attrService.selectFsStoreProductAttrByProductId(productId);
        return R.ok().put("data", product).put("attrs", attrs);
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:remove')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE, isStoreLog = true,
            logParamExpression = "#p0.length>1?new String[]{'商品','批量删除商品信息'}: new String[]{'商品','删除商品信息'}")
    @DeleteMapping("/{productIds}")
    public R remove(@PathVariable Long[] productIds) {
        return fsStoreProductService.deleteFsStoreProductByIds(productIds);
    }


    /**
     * 批量复制商品
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:bulkCopy')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE, isStoreLog = true,
            logParamExpression = "#p0.length>1?new String[]{'商品','批量复制商品信息'}: new String[]{'商品','复制商品信息'}")
    @GetMapping("/bulkCopy/{productIds}")
    public R bulkCopy(@PathVariable Long[] productIds) {
        return fsStoreProductService.bulkCopyFsStoreProductByIds(productIds);
    }

    @ApiOperation(value = "生成属性")
    @PostMapping(value = "/genFormatAttr/{productId}")
    public ResponseEntity genFormatAttr(@PathVariable Long productId, @RequestBody String jsonStr, Long[] stores) {
        return new ResponseEntity<>(fsStoreProductService.getFormatAttr(productId, jsonStr, stores), HttpStatus.OK);
    }


    @GetMapping("/getStoreProductAttrValueList")
    public TableDataInfo getStoreProductAttrValueList(FsProductAttrValueParam param) {
        startPage();
        List<FsStoreProductAttrValueVO> list = attrValueService.selectFsStoreProductAttrValueListVO(param);
        return getDataTable(list);
    }

    @ApiOperation("获取推广商品列表")
    @GetMapping("/getStoreTuiProductAttrValueList")
    public TableDataInfo getStoreTuiProductAttrValueList(FsStoreTuiProductAttrValueParam param, HttpServletRequest request) {
        startPage();
        List<FsStoreTuiProductAttrValueVO> list = attrValueService.selectStoreTuiProductAttrValueVOList(param);
        return getDataTable(list);
    }

    @GetMapping("/listBySearch")
    public R listBySearCh(FsStoreProductScrm product) {
        List<FsStoreProductScrm> list = fsStoreProductService.selectFsStoreProductList(product);
        return R.ok().put("data", list);
    }

    /**
     * 获取店铺商品表字段
     */
    @GetMapping("/getStoreProductColumns")
    public R getStoreProductColumns() {
        List<Map<String, String>> list = fsStoreProductService.getStoreProductColumns();
        return R.ok().put("data", list);
    }


    /**
     * 同步商品到580商城
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:sync')")
    @Log(title = "同步商品到580医院", businessType = BusinessType.DELETE, isStoreLog = true,
            logParamExpression = "#p0.length>1?new String[]{'商品','同步商品到580医院'}: new String[]{'商品','同步商品到580医院'}")
    @PostMapping("/sync580/{productIds}")
    public R sync(@PathVariable Long[] productIds) {
        fsStoreHospital580ScrmService.SynDrugToHospital580(productIds);
        return R.ok("同步成功");
    }

    /**
     * 同步商品到580商城
     */
    @PreAuthorize("@ss.hasPermi('store:storeProduct:update')")
    @Log(title = "批量下架商品", businessType = BusinessType.DELETE, isStoreLog = true,
            logParamExpression = "#p0.length>1?new String[]{'商品','下架'}: new String[]{'商品','下架'}")
    @PostMapping("/updateFsStoreProductIsShowBatch/{productIds}")
    public R updateFsStoreProductIsShowBatch(@PathVariable Long[] productIds) {
        if (productIds.length > 0) {
            fsStoreProductService.updateFsStoreProductIsShowBatch(productIds);
        }
        return R.ok("操作完成");
    }

    @Log(title = "总后台商品协议过期提醒", businessType = BusinessType.OTHERe)
    /**
     * 商品资质信息提示
     *
     * @return
     */
    @GetMapping("/productNoticeInfo")
    public R getProductNoticeInfo() {
        List<String> productNoticeInfo = fsStoreProductService.getProductNoticeInfo(null);
        if (!CollectionUtils.isEmpty(productNoticeInfo)) {
            return R.ok().put("code", 200).put("data", productNoticeInfo);
        }
        return R.ok().put("code", 0);
    }


    /**
     * 商品审核日志
     * */
    @PreAuthorize("@ss.hasPermi('his:storeProduct:auditLog')")
    @GetMapping("/auditLog/{storeId}")
    public R auditLog(@PathVariable Long storeId){
        return R.ok().put("auditLog",storeAuditLogUtil.selectOperLogByMainId(storeId,"商品"));
    }

    /**
     * 商品复制
     * @param product 商品对象
     * @return R
     * */
    @PreAuthorize("@ss.hasPermi('his:storeProduct:copyProduct')")
    @PostMapping("/copyProduct")
    @Log(title = "复制商品", businessType = BusinessType.INSERT, isStoreLog = true, logParam = {"商品", "复制商品"})
    public R copyProduct(@RequestBody FsStoreProductScrm product) {
        return fsStoreProductService.copyProduct(product);
    }
}
