package org.example.Impl;

import org.example.Entity.BaseResponse.BaseResponse;
import org.example.Utils.*;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Path;
import java.sql.Types;
import java.util.Map;

import static org.example.Utils.NativeExtensionUtils.ToInt32;
import static org.example.Utils.NativeExtensionUtils.isNullOrEmpty;

@Service
public class FileImpl extends OptBaseImpl {

    private final JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedJdbcTemplate;

    public FileImpl(JdbcTemplate jdbcTemplate) {
        super();
        this.jdbcTemplate = jdbcTemplate;
    }

    private String toTempFileName(String filename) {
        if (!isNullOrEmpty(filename) && !filename.endsWith("temp")) {
            return StringFormat.format("{0}.{1}", filename, "temp");
        }

        return filename;
    }

    public BaseResponse Check(Map<String, Object> fInfos) {
        String menucode = String.valueOf(fInfos.get("menucode"));
        String value = String.valueOf(fInfos.get("value"));
        String filename = String.valueOf(fInfos.get("filename"));
        String fileNo = String.valueOf(fInfos.get("fileNo"));

        BaseResponse _tempR = FileUtil.checkExistsFile(StringFormat.format(WebConfigUtil.PubModelAccFilePath, menucode, value, fileNo), toTempFileName(filename));
        BaseResponse response = FileUtil.checkExistsFile(StringFormat.format(WebConfigUtil.PubModelAccFilePath, menucode, value, fileNo), filename);

        response.setOther(("1".equals(_tempR.getOther() != null ? _tempR.getOther().toString() : "") || "1".equals(response.getOther() != null ? response.getOther().toString() : "")) ? 1 : 0);
        return response;
    }


    public BaseResponse Save(byte[] buffer, Map<String, Object> fInfos) {
        String username = (String) fInfos.getOrDefault("username", "");
        String userid = (String) fInfos.getOrDefault("userid", "");
        String menucode = (String) fInfos.getOrDefault("menucode", "");
        String key = (String) fInfos.getOrDefault("key", "");
        String value = (String) fInfos.getOrDefault("value", "");
        String filename = (String) fInfos.getOrDefault("filename", "");
        String filesize = (String) fInfos.getOrDefault("filesize", "");
        String fileNo = (String) fInfos.getOrDefault("fileNo", "");

        int position = ToInt32(fInfos.getOrDefault("position", ""));

//        方法中参数继承,需修改
//        return FileUtil.SaveFile(buffer, position,0, StringFormat.format(WebConfigUtil.PubModelAccFilePath, menucode, value, fileNo), filename,AppDomain);
        return null;
    }

    public BaseResponse AddFileInfo(Map<String, Object> fInfos) {
        BaseResponse response = new BaseResponse();
        String menucode = (String) fInfos.get("menucode");
        String value = (String) fInfos.get("value");
        String fileNo = (String) fInfos.get("fileNo");
        String filePath = StringFormat.format((String) WebConfigUtil.PubModelAccFilePath, menucode, value, fileNo);
        String filename = (String) fInfos.get("filename");//需修改
        String tempFilename = toTempFileName(filePath);
        String sourceFilePath = (String) fInfos.get("sourceFilePath");//需修改

        //需修改
//        FileUtil.MoveTo(sourceFilePath, filePath, filename, AttcPath);

        try {
            String sql = "INSERT INTO dbo.T_SystemFileTab (" +
                    "FileName, FileSize, FilePath, SpeciesNo, MenuCode, " +
                    "PrimaryKey, PrimaryValue, CreateID, CreateName, CreateDate, FileState) " +
                    "VALUES (:FileName, :FileSize, :FilePath, :SpeciesNo, :MenuCode, " +
                    ":PrimaryKey, :PrimaryValue, :CreateID, :CreateName, GETDATE(), 0); " +
                    "SELECT @@IDENTITY AS id;";

            String fileName = new File(fInfos.get("filename").toString()).getName();

            // 构建参数（对应DbParameter数组）
            MapSqlParameterSource params = new MapSqlParameterSource()
                    .addValue("FileName", fileName, Types.VARCHAR)
                    .addValue("FileSize", fInfos.get("filesize"), Types.VARCHAR)
                    .addValue("FilePath", StringFormat.format(WebConfigUtil.PubModelAccFilePath,
                            fInfos.get("menucode"),
                            fInfos.get("value"),
                            fInfos.get("fileNo")), Types.VARCHAR)
                    .addValue("SpeciesNo", fInfos.get("fileNo"), Types.VARCHAR)
                    .addValue("MenuCode", fInfos.get("menucode"), Types.VARCHAR)
                    .addValue("PrimaryKey", fInfos.get("key"), Types.VARCHAR)
                    .addValue("PrimaryValue", fInfos.get("value"), Types.VARCHAR)
                    .addValue("CreateID", Integer.parseInt(fInfos.get("userid").toString()), Types.INTEGER)
                    .addValue("CreateName", fInfos.get("username"), Types.VARCHAR);
            int result = ToInt32(namedJdbcTemplate.queryForObject(sql, params, Object.class));

            response.setSuccess(result > 0);
            response.setOther(result);

        } catch (Exception ex) {
            response.setMsg(ex.getMessage());
        }
        return response;
    }
}
