package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/fonchain/fonchain-artistinfo/cmd/internal/dao"
	"github.com/fonchain/fonchain-artistinfo/cmd/model"
	"github.com/fonchain/fonchain-artistinfo/pb/artist"
	"github.com/fonchain/fonchain-artistinfo/pb/artistInfoUser"
	"github.com/fonchain/fonchain-artistinfo/pb/contract"
	contractMicroservice "github.com/fonchain/fonchain-artistinfo/pb/contract_microservice"
	db "github.com/fonchain/fonchain-artistinfo/pkg/db"
	"github.com/fonchain/fonchain-artistinfo/pkg/m"
	"github.com/fonchain/fonchain-artistinfo/pkg/service"
	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

type IContract interface {
	CreateContract(req *contract.CreateContractRequest) (rep *contract.CreateContractRespond, err error)
	ContractListMgmt(req *contract.ContractListMgmtRequest) (rep *contract.ContractListMgmtRespond, err error)
	ContractList(req *contract.ContractListRequest) (rep *contract.ContractListRespond, err error)
	SignContract(req *contract.SignContractRequest) (rep *contract.SignContractRespond, err error)

	// FinishContract(req *contract.FinishContractRequest) (rep *contract.FinishContractRespond, err error)
	// ContractList(req *contract.ContractListRequest) (rep *contract.ContractListRespond, err error)
	// ContractTxList(req *contract.ContractTxListRequest) (rep *contract.ContractTxListRespond, err error)
	// UpdateContract(req *contract.UpdateContractRequest) (rep *contract.UpdateContractRespond, err error)
	// UpdateContractTx(req *contract.UpdateContractTxRequest) (rep *contract.UpdateContractTxRespond, err error)
	// GetContract(req *contract.GetContractRequest) (rep *contract.ContractData, err error)
}

func NewContract() IContract {
	return &Contract{}
}

type Contract struct {
}

func (a *Contract) CreateContract(req *contract.CreateContractRequest) (rep *contract.CreateContractRespond, err error) {
	rep = &contract.CreateContractRespond{}

	//遇到错误数据库回滚
	tx := db.DB.Begin()

	userInfo, err := NewArtistInfo().FindUser(&artistInfoUser.FindUserRequest{
		MgmtArtistUid: req.ArtistUid,
		IsArtist:      true,
	})

	if err != nil {
		return
	}
	if userInfo.Id == 0 {
		return
	}

	switch req.Type {
	//1 画家合同（不涉及画家的画作）
	case 1:

		//查看画家合同是否已经存在,不存在继续
		if err = dao.GetMgmtContractByArtistUid(req.ArtistUid, req.Type); err == gorm.ErrRecordNotFound {
			var uid uuid.UUID
			if uid, err = uuid.NewV4(); err != nil {
				err = errors.New(m.ERROR_UID)
				return
			}

			//创建画家合同
			contract := &model.Contract{
				Uid:       uid.String(),
				ArtistUid: req.ArtistUid,
				Type:      1,
				State:     1,
				Status:    2,
				LockTime:  userInfo.LatestLockTime,
			}

			if err = dao.CreateArtistContract(tx, contract); err != nil {
				return
			}
		} else {
			return
		}

	case 2:
		for _, v := range req.ArtworkUid {
			//查看画作合同是否已经存在,不存在继续，类型2、6
			if err = dao.GetMgmtContractByArtworkUid(v, 2); err == gorm.ErrRecordNotFound {
			} else {
				return
			}

			if err = dao.GetMgmtContractByArtworkUid(v, 6); err == gorm.ErrRecordNotFound {

			} else {
				return
			}
		}

		//创建画家画作合同，类型2,如果批次选择多个画作的话，那么多个画在一个合同中
		if err = dao.CreateArtworkContract(tx, req.ArtworkUid, req.ArtistUid, 2, userInfo.LatestLockTime); err != nil {
			tx.Rollback()
			return
		}

		//创建画家画作合同，类型6
		if err = dao.CreateArtworkContract(tx, req.ArtworkUid, req.ArtistUid, 6, userInfo.LatestLockTime); err != nil {
			tx.Rollback()
			return
		}

	case 3:
		for _, v := range req.ArtworkUid {
			//查看画作合同是否已经存在,不存在继续，类型3
			if err = dao.GetMgmtContractByArtworkUid(v, 3); err == gorm.ErrRecordNotFound {
			} else {
				return
			}

			//创建画家画作合同，类型3
			if err = dao.CreateArtworkContract(tx, req.ArtworkUid, req.ArtistUid, 3, userInfo.LatestLockTime); err != nil {
				tx.Rollback()
				return
			}
		}

	case 5:
		for _, v := range req.ArtworkUid {
			//查看画作合同是否已经存在,不存在继续，类型5
			if err = dao.GetMgmtContractByArtworkUid(v, 5); err == gorm.ErrRecordNotFound {
			} else {
				return
			}
			//创建画家画作合同，类型3
			if err = dao.CreateArtworkContract(tx, req.ArtworkUid, req.ArtistUid, 5, userInfo.LatestLockTime); err != nil {
				tx.Rollback()
				return
			}
		}

	default:
		err = errors.New("type值出错!")
		return

	}

	tx.Commit()
	return
}

func (a *Contract) ContractListMgmt(req *contract.ContractListMgmtRequest) (rep *contract.ContractListMgmtRespond, err error) {
	rep = &contract.ContractListMgmtRespond{}
	//查看是否有该画家
	if err = dao.GetArtistNoByUid(req.ArtistUid); err != nil {
		return
	}

	//合同分页查询操作
	if req.Page < 1 {
		req.Page = 1
	}
	if req.Num < 1 {
		req.Num = 15
	}
	offset := (req.Page - 1) * req.Num

	//获取该用户的所有合同
	contracts, err := dao.GetContractList(req.ArtistUid, req.Num, offset)
	if err != nil {
		return
	}
	rep.Data = contracts

	return
}

func (a *Contract) ContractList(req *contract.ContractListRequest) (rep *contract.ContractListRespond, err error) {

	//查看是否有该画家
	user, err := dao.GetArtistInfoById(req.ID)
	if err != nil {
		return
	}

	ContractData, err := dao.ContractList(user.MgmtArtistUid, req.State)
	if err != nil {
		return
	}

	rep = &contract.ContractListRespond{
		Data: ContractData,
	}

	return
}

func (a *Contract) SignContract(req *contract.SignContractRequest) (rep *contract.SignContractRespond, err error) {
	rep = &contract.SignContractRespond{}

	//遇到错误数据库回滚
	tx := db.DB.Begin()

	//根据合同id获取具体合同信息
	contractInfo, err := dao.GetContractInfo(req.ContractId)
	if err != nil {
		return
	}

	artistInfo, err := dao.GetArtistInfoById(req.ID)
	if err != nil {
		return
	}

	detailRequest := &artist.DetailRequest{
		Uid: artistInfo.MgmtArtistUid,
	}
	artistDetailResponse, err := service.GrpcArtistImpl.ArtistDetail(context.Background(), detailRequest)
	if err != nil {
		return rep, err
	}

	if contractInfo.Type != 4 && contractInfo.Type != 7 {

		switch contractInfo.Type {
		case 1:
			var ContractNo = fmt.Sprintf("TF_%d", time.Now().UnixNano())
			endTime := time.Now().AddDate(1, 0, -1)
			parameterMap := make((map[string]string), 0)

			// 一、 模板填充
			parameterMap["PartyAName"] = artistDetailResponse.ProfileInfo.Name
			parameterMap["PartyAAddress"] = artistDetailResponse.ProfileInfo.Address
			parameterMap["PartyAIdentityCard"] = artistDetailResponse.ProfileInfo.CardId
			parameterMap["PartyATelNum"] = artistDetailResponse.ProfileInfo.Phone
			parameterMap["PartyBRule"] = "240"
			parameterMap["SettleNum"] = "2"
			parameterMap["SettleSec"] = "100"
			parameterMap["ActivityNum"] = "2"
			parameterMap["SettlerTypeFour"] = "2"
			parameterMap["PowerDay"] = "5"
			parameterMap["EffectStartYear"] = fmt.Sprintf("%d", time.Now().Year())
			parameterMap["EffectStartMonth"] = fmt.Sprintf("%d", time.Now().Month())
			parameterMap["EffectStartDay"] = fmt.Sprintf("%d", time.Now().Day())
			parameterMap["EffectEndYear"] = fmt.Sprintf("%d", endTime.Year())
			parameterMap["EffectEndMonth"] = fmt.Sprintf("%d", endTime.Month())
			parameterMap["EffectEndDay"] = fmt.Sprintf("%d", endTime.Day())
			parameterMap["PartyBLegal"] = "胡婷"

			//将map转换为string类型
			parameterMapType, err := json.Marshal(parameterMap)
			if err != nil {
				return rep, err
			}

			generateContractRequest := &contractMicroservice.GenerateContractRequest{
				TemplateId:   "一手画市场18",
				ContractId:   ContractNo,
				ParameterMap: string(parameterMapType),
			}
			generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
			if err != nil {
				return rep, err
			}

			//二、 自动签署
			extSignAutoRequest := &contractMicroservice.ExtSignAutoRequest{
				TransactionId: fmt.Sprintf("TFAU_%d", time.Now().UnixNano()),
				ContractId:    ContractNo,
				CustomerId:    "1A958BFD01E6551D06381DA6C0B19259",
				DocTitle:      fmt.Sprintf("TFAU_%d", time.Now().UnixNano()),
				SignKeyword:   "受托方（乙方）",
				SignatureId:   "1668589742383450",
				KeyX:          "120",
				KeyY:          "0",
			}

			_, err = service.ContractImpl.ExtSignAuto(context.Background(), extSignAutoRequest)
			if err != nil {
				return rep, err
			}

			//更新合同表，将合同的下载、在线、id保存
			err = dao.UpdateContract(tx, contractInfo.Uid, generateContractResponse.ViewPdfUrl, generateContractResponse.DownloadUrl, ContractNo)
			if err != nil {
				return rep, err
			}

		case 2:

			var ContractNo = fmt.Sprintf("TF_%d", time.Now().UnixNano())
			var parameterMap = make(map[string]string)
			endTime := time.Now().AddDate(1, 0, -1)
			parameterMap["ContractNo"] = ContractNo
			parameterMap["PartyAName"] = artistDetailResponse.ProfileInfo.Name
			parameterMap["PartyAAddress"] = artistDetailResponse.ProfileInfo.Address
			parameterMap["PartyAIdentityCard"] = artistDetailResponse.ProfileInfo.CardId
			parameterMap["PartyATelNum"] = artistDetailResponse.ProfileInfo.Phone
			parameterMap["SettleNum"] = "2"
			parameterMap["SettleSecOne"] = "0"
			parameterMap["SettleSecTwo"] = "100"
			parameterMap["ActivityNum"] = "2"
			parameterMap["SettlerTypeFour"] = "2"
			parameterMap["PowerDay"] = "5"
			parameterMap["EffectStartYear"] = fmt.Sprintf("%d", time.Now().Year())
			parameterMap["EffectStartMonth"] = fmt.Sprintf("%d", time.Now().Month())
			parameterMap["EffectStartDay"] = fmt.Sprintf("%d", time.Now().Day())
			parameterMap["EffectEndYear"] = fmt.Sprintf("%d", endTime.Year())
			parameterMap["EffectEndMonth"] = fmt.Sprintf("%d", endTime.Month())
			parameterMap["EffectEndDay"] = fmt.Sprintf("%d", endTime.Day())
			parameterMap["PartyBLegal"] = "邬侨华"

			//将map转换为string类型
			parameterMapType, err := json.Marshal(parameterMap)
			if err != nil {
				return rep, err
			}

			generateContractRequest := &contractMicroservice.GenerateContractRequest{
				TemplateId:   "著作权代理转让服务合同20",
				ContractId:   ContractNo,
				ParameterMap: string(parameterMapType),
			}
			generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
			if err != nil {
				return rep, err
			}

			//二、 自动签署
			extSignAutoRequest := &contractMicroservice.ExtSignAutoRequest{
				TransactionId: fmt.Sprintf("TFAU_%d", time.Now().UnixNano()),
				ContractId:    ContractNo,
				CustomerId:    "F49C748A0C06431BC620354F4491BD37",
				DocTitle:      fmt.Sprintf("TFAU_%d", time.Now().UnixNano()),
				SignKeyword:   "受托方（乙方）",
				SignatureId:   "1668589763366246",
				KeyX:          "120",
				KeyY:          "0",
			}

			_, err = service.ContractImpl.ExtSignAuto(context.Background(), extSignAutoRequest)
			if err != nil {
				return rep, err
			}

			//更新合同表，将合同的下载、在线、id保存
			err = dao.UpdateContract(tx, contractInfo.Uid, generateContractResponse.ViewPdfUrl, generateContractResponse.DownloadUrl, ContractNo)
			if err != nil {
				return rep, err
			}

		case 3:
			var ContractNo = fmt.Sprintf("TF_%d", time.Now().UnixNano())

			//获取画作信息
			artworkDetailResponse, err := dao.GetArtworkProfileByArtworkUid(contractInfo.ArtworkUid)
			if err != nil {
				return rep, err
			}

			var parameterMap = make(map[string]string)
			parameterMap["PartyAName"] = artistDetailResponse.ProfileInfo.Name
			parameterMap["PartyAIdCard"] = artistDetailResponse.ProfileInfo.CardId
			parameterMap["ArtworkName"] = artworkDetailResponse.ProfileInfo.ArtworkName
			parameterMap["Year"] = fmt.Sprintf("%d", time.Now().Year())
			parameterMap["Month"] = fmt.Sprintf("%d", time.Now().Month())
			parameterMap["Day"] = fmt.Sprintf("%d", time.Now().Day())

			//将map转换为string类型
			parameterMapType, err := json.Marshal(parameterMap)
			if err != nil {
				return rep, err
			}

			generateContractRequest := &contractMicroservice.GenerateContractRequest{
				TemplateId:   "登记授权委托书18",
				ContractId:   ContractNo,
				ParameterMap: string(parameterMapType),
			}
			generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
			if err != nil {
				return rep, err
			}

			//更新合同表，将合同的下载、在线、id保存
			err = dao.UpdateContract(tx, contractInfo.Uid, generateContractResponse.ViewPdfUrl, generateContractResponse.DownloadUrl, ContractNo)
			if err != nil {
				return rep, err
			}

		case 5:

			//获取画作信息
			artworkDetailResponse, err := dao.GetArtworkProfileByArtworkUid(contractInfo.ArtworkUid)
			if err != nil {
				return rep, err
			}

			var ContractNo = fmt.Sprintf("TF_%d", time.Now().UnixNano())

			var parameterMap = make(map[string]string)
			parameterMap["ArtworkName"] = artworkDetailResponse.ProfileInfo.ArtworkName
			parameterMap["Year"] = fmt.Sprintf("%d", time.Now().Year())
			parameterMap["Month"] = fmt.Sprintf("%d", time.Now().Month())
			parameterMap["Day"] = fmt.Sprintf("%d", time.Now().Day())

			//将map转换为string类型
			parameterMapType, err := json.Marshal(parameterMap)
			if err != nil {
				return rep, err
			}

			generateContractRequest := &contractMicroservice.GenerateContractRequest{
				TemplateId:   "作品登记承诺书16",
				ContractId:   ContractNo,
				ParameterMap: string(parameterMapType),
			}
			generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
			if err != nil {
				return rep, err
			}

			//更新合同表，将合同的下载、在线、id保存
			err = dao.UpdateContract(tx, contractInfo.Uid, generateContractResponse.ViewPdfUrl, generateContractResponse.DownloadUrl, ContractNo)
			if err != nil {
				return rep, err
			}

		case 6:
			ArtistUids := strings.Split(contractInfo.ArtistUid, ",")

			type dynamic struct {
				InsertWay               int        `json:"insertWay"`
				Keyword                 string     `json:"keyword"`
				CellHeight              float64    `json:"cellHeight"`
				ColWidthPercent         []int      `json:"colWidthPercent"`
				TheFirstHeader          string     `json:"theFirstHeader"`
				CellHorizontalAlignment int        `json:"cellHorizontalAlignment"`
				CellVerticalAlignment   int        `json:"cellVerticalAlignment"`
				Headers                 []string   `json:"headers"`
				Datas                   [][]string `json:"datas"`
			}
			var dynamicList []dynamic
			var dynamicOne dynamic

			dynamicOne.InsertWay = 1
			dynamicOne.Keyword = "附表 1"
			dynamicOne.CellHeight = 16.0
			dynamicOne.ColWidthPercent = []int{6, 6, 20, 10, 10}
			// dynamicOne.TheFirstHeader =
			dynamicOne.CellHorizontalAlignment = 1
			dynamicOne.CellVerticalAlignment = 5
			dynamicOne.Headers = []string{"序号", "作品名称", "哈希值", "著作权取得方式（原始/继受）", "继受取得的证明文件"}

			for k, v := range ArtistUids {
				//获取画作信息
				artworkDetailResponse, err := dao.GetArtworkProfileByArtworkUid(v)
				if err != nil {
					return rep, err
				}

				var tmps []string
				tmps = append(tmps, fmt.Sprintf("%d", k+1))
				tmps = append(tmps, artworkDetailResponse.ProfileInfo.ArtistName) //获取画作名字
				tmps = append(tmps, artworkDetailResponse.DigiInfo.CopyrightHash) //获取版权hash
				tmps = append(tmps, "原始")
				tmps = append(tmps, "")
				dynamicOne.Datas = append(dynamicOne.Datas, tmps)
			}

			dynamicList = append(dynamicList, dynamicOne)

			dyByte, err := json.Marshal(dynamicList)
			if err != nil {
				return rep, err
			}

			ContractNo := fmt.Sprintf("TF_%d", time.Now().UnixNano()+1000)

			//一、 模板填充
			var parameterMap = make(map[string]string)
			parameterMap["PartyBLegal"] = artistDetailResponse.ProfileInfo.Name

			//将map转换为string类型
			parameterMapType, err := json.Marshal(parameterMap)
			if err != nil {
				return rep, err
			}

			var viewPdfUrl string
			var downloadUrl string

			generateContractRequest := &contractMicroservice.GenerateContractRequest{
				ContractId:    ContractNo,
				ParameterMap:  string(parameterMapType),
				DynamicTables: string(dyByte),
			}

			if len(ArtistUids) > 30 {

				return rep, errors.New("选择画作条数过多")

			} else if len(ArtistUids) <= 15 {
				generateContractRequest.TemplateId = "著作权代理转让服务合同——附表152"
				generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
				if err != nil {
					return rep, err
				}

				viewPdfUrl = generateContractResponse.ViewPdfUrl
				downloadUrl = generateContractResponse.DownloadUrl

			} else {
				generateContractRequest.TemplateId = "著作权代理转让服务合同——附表302"
				generateContractResponse, err := service.ContractImpl.GenerateContract(context.Background(), generateContractRequest)
				if err != nil {
					return rep, err
				}

				viewPdfUrl = generateContractResponse.ViewPdfUrl
				downloadUrl = generateContractResponse.DownloadUrl
			}

			//二、 自动签署
			extSignAutoRequest := &contractMicroservice.ExtSignAutoRequest{
				TransactionId: fmt.Sprintf("TFAU_%d", time.Now().UnixNano()+1000),
				ContractId:    ContractNo,
				CustomerId:    "F49C748A0C06431BC620354F4491BD37",
				DocTitle:      fmt.Sprintf("TFAU_%d", time.Now().UnixNano()),
				SignKeyword:   "受托方（乙方）",
				SignatureId:   "1668589763366246",
				KeyX:          "120",
				KeyY:          "0",
			}

			_, err = service.ContractImpl.ExtSignAuto(context.Background(), extSignAutoRequest)
			if err != nil {
				return rep, err
			}

			//更新合同表，将合同的下载、在线、id保存
			err = dao.UpdateContract(tx, contractInfo.Uid, viewPdfUrl, downloadUrl, ContractNo)
			if err != nil {
				tx.Rollback()
				return rep, err
			}
		default:
			return rep, errors.New("type出错")
		}
	}

	//上面数据库没有错误就执行,上面修改的值下面会使用到
	tx.Commit()

	transactionId := fmt.Sprintf("TFTX_%d", time.Now().UnixNano())

	var signKeyword string

	//从新根据合同id获取具体合同信息
	contractInfo, err = dao.GetContractInfo(req.ContractId)
	if err != nil {
		return
	}

	if contractInfo.Type == 1 || contractInfo.Type == 2 || contractInfo.Type == 6 {

		signKeyword = "委托方（甲方）"
	}
	if contractInfo.Type == 3 {
		signKeyword = "委托人签字："
	}
	if contractInfo.Type == 4 {
		signKeyword = "画家签字："
	}
	if contractInfo.Type == 5 {
		signKeyword = "申请人（签章）："
	}
	signShowTime := "1"
	if contractInfo.Type == 5 || contractInfo.Type == 3 || contractInfo.Type == 6 {
		signShowTime = "2"
	}
	// 手动签署
	extSignRequest := &contractMicroservice.ExtSignRequest{
		TransactionId:     transactionId,
		ContractId:        contractInfo.ContractId,
		CustomerId:        "",
		ReturnUrl:         "",
		DocTitle:          "",
		OpenEnvironment:   "",
		MobileSignType:    "",
		SignKeyword:       "",
		Keyx:              "",
		Keyy:              "",
		SignatureShowTime: "",
		PcHandSignature:   "",
	}

	_, err = service.ContractImpl.ExtSign(context.Background(), extSignRequest)
	if err != nil {
		return rep, err
	}

	return

}

// func (a *Contract) FinishContract(req *contract.FinishContractRequest) (rep *contract.FinishContractRespond, err error) {
// 	rep = &contract.FinishContractRespond{}

// 	tx := db.DB.Begin()
// 	//更新合同状态并获取合同信息
// 	contract, err := dao.FinishContract(tx, req.TransactionId)
// 	if err != nil {
// 		tx.Rollback()
// 		return nil, err
// 	}

// 	//查看画作是否已经状态改变，没有则改变  无用
// 	if err = dao.UpdateArtworkState(tx, contract.ID); err != nil {
// 		tx.Rollback()
// 		return
// 	}

// 	var tmp struct {
// 		Uid int32 `json:"uid"`
// 	}
// 	tmp.Uid = contract.BatchId
// 	tmpByte, _ := json.Marshal(&tmp)

// 	if contract.Type == 4 {
// 		_, err = util.Post("https://ms.fontree.cn/mgmt/artworktx/updatebatchtype", string(tmpByte))
// 		if err != nil {
// 			zap.L().Error("post request err", zap.Error(err))
// 			return
// 		}
// 	}

// 	if contract.Type == 7 {
// 		_, err = util.Post("https://ms.fontree.cn/mgmt/artworktx/updatebatchtypecopy", string(tmpByte))
// 		if err != nil {
// 			zap.L().Error("post request err", zap.Error(err))
// 			return
// 		}
// 	}

// 	tx.Commit()
// 	return
// }

// func (a *Contract) ContractList(req *contract.ContractListRequest) (rep *contract.ContractListRespond, err error) {

// 	rep, err = dao.ContractList(req)

// 	return
// }

// func (a *Contract) GetContract(req *contract.GetContractRequest) (rep *contract.ContractData, err error) {

// 	rep, err = dao.GetContract(int32(req.Id))

// 	return
// }
// func (a *Contract) ContractTxList(req *contract.ContractTxListRequest) (rep *contract.ContractTxListRespond, err error) {

// 	rep, err = dao.ContractTxList(req)

// 	return
// }

// func (a *Contract) UpdateContract(req *contract.UpdateContractRequest) (rep *contract.UpdateContractRespond, err error) {
// 	rep = &contract.UpdateContractRespond{}
// 	err = dao.UpdateContract(req)

// 	return
// }

// func (a *Contract) UpdateContractTx(req *contract.UpdateContractTxRequest) (rep *contract.UpdateContractTxRespond, err error) {
// 	rep = &contract.UpdateContractTxRespond{}
// 	err = dao.UpdateContractTx(req.TransactionId, int32(req.ID))

// 	return
// }
