package api

import (
	"box-cost/db/model"
	"fmt"

	"github.com/xuri/excelize/v2"
)

type ProduceBillExcel struct {
	Offset int
	Row    int

	Title string //标题

	Excel *excelize.File

	SheetName string

	AlignCenterStyle int

	Content    *model.ProduceBill
	Signatures []*model.Signature

	IsPdf string
}

func (b *ProduceBillExcel) drawTitle() error {
	b.Row++
	//是打印
	startCell := fmt.Sprintf("A%d", b.Row)
	marginLeft := excelize.PageMarginLeft(0.1)
	endCell := fmt.Sprintf("L%d", b.Row)
	if b.Content.IsPrint {
		b.Excel.SetColWidth(b.SheetName, "A", "C", 11)
		b.Excel.SetColWidth(b.SheetName, "D", "D", 10)
		b.Excel.SetColWidth(b.SheetName, "E", "E", 7)
		b.Excel.SetColWidth(b.SheetName, "F", "F", 10)
		b.Excel.SetColWidth(b.SheetName, "G", "G", 7)
		b.Excel.SetColWidth(b.SheetName, "H", "H", 6.5)
		b.Excel.SetColWidth(b.SheetName, "I", "J", 9)
		b.Excel.SetColWidth(b.SheetName, "K", "K", 12)
		b.Excel.SetColWidth(b.SheetName, "L", "L", 14)

	} else {
		// 不是打印
		endCell = fmt.Sprintf("H%d", b.Row)
		marginLeft = excelize.PageMarginLeft(0.6)
		b.Excel.SetColWidth(b.SheetName, "A", "B", 17)
		b.Excel.SetColWidth(b.SheetName, "C", "C", 12)
		b.Excel.SetColWidth(b.SheetName, "D", "D", 6)
		b.Excel.SetColWidth(b.SheetName, "E", "G", 12)
		b.Excel.SetColWidth(b.SheetName, "H", "H", 20)
		// 是覆膜
		if b.Content.IsLam {
			endCell = fmt.Sprintf("I%d", b.Row)
			marginLeft = excelize.PageMarginLeft(0.2)
			b.Excel.SetColWidth(b.SheetName, "A", "A", 14)
			b.Excel.SetColWidth(b.SheetName, "B", "C", 14)
			// 覆膜规格
			// b.Excel.SetColWidth(b.SheetName, "C", "C", 16)
			b.Excel.SetColWidth(b.SheetName, "D", "D", 10)
			b.Excel.SetColWidth(b.SheetName, "E", "F", 11)
			b.Excel.SetColWidth(b.SheetName, "G", "H", 12)
			b.Excel.SetColWidth(b.SheetName, "I", "I", 16)

		}

	}
	b.Excel.SetPageMargins(b.SheetName, marginLeft)
	err := b.Excel.MergeCell(b.SheetName, startCell, endCell)
	if err != nil {
		return err
	}

	style, err := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center"},
		Font:      &excelize.Font{Bold: true, Size: 18}})
	if err != nil {
		return err
	}
	err = b.Excel.SetCellStyle(b.SheetName, startCell, startCell, style)
	if err != nil {
		return err
	}
	b.Excel.SetRowHeight(b.SheetName, b.Row, 23)
	b.Excel.SetCellValue(b.SheetName, startCell, b.Title)
	return nil
}

func (b *ProduceBillExcel) drawSubTitles() error {
	b.Row++
	styleLeft, err := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "left", Vertical: "center"},
		Font:      &excelize.Font{Size: 11}})
	if err != nil {
		return err
	}
	styleRight, err := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "right", Vertical: "center"},
		Font:      &excelize.Font{Size: 11}})
	if err != nil {
		return err
	}

	drawLeft := func(rowIndex int, value string) error {
		//左边1
		left1Cell := fmt.Sprintf("A%d", rowIndex)
		err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("I%d", rowIndex))
		if err != nil {
			return err
		}
		err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
		if err != nil {
			return err
		}
		b.Excel.SetCellValue(b.SheetName, left1Cell, value)
		return nil
	}

	drawRight := func(rowIndex int, value string) error {
		right1Cell := fmt.Sprintf("J%d", rowIndex)
		err = b.Excel.MergeCell(b.SheetName, right1Cell, fmt.Sprintf("L%d", rowIndex))
		if err != nil {
			return err
		}
		err = b.Excel.SetCellStyle(b.SheetName, right1Cell, right1Cell, styleRight)
		if err != nil {
			return err
		}
		b.Excel.SetCellValue(b.SheetName, right1Cell, value)
		return nil
	}

	drawLall := func(rowIndex int, value string) error {
		//左边1
		left1Cell := fmt.Sprintf("A%d", rowIndex)
		err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("L%d", rowIndex))
		if err != nil {
			return err
		}
		err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
		if err != nil {
			return err
		}
		b.Excel.SetCellValue(b.SheetName, left1Cell, value)
		return nil
	}

	if !b.Content.IsPrint {
		drawLeft = func(rowIndex int, value string) error {
			//左边1
			left1Cell := fmt.Sprintf("A%d", rowIndex)
			err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("F%d", rowIndex))
			if err != nil {
				return err
			}
			err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
			if err != nil {
				return err
			}
			b.Excel.SetCellValue(b.SheetName, left1Cell, value)
			return nil
		}

		drawRight = func(rowIndex int, value string) error {
			right1Cell := fmt.Sprintf("G%d", rowIndex)
			err = b.Excel.MergeCell(b.SheetName, right1Cell, fmt.Sprintf("H%d", rowIndex))
			if err != nil {
				return err
			}
			err = b.Excel.SetCellStyle(b.SheetName, right1Cell, right1Cell, styleRight)
			if err != nil {
				return err
			}
			b.Excel.SetCellValue(b.SheetName, right1Cell, value)
			return nil
		}

		drawLall = func(rowIndex int, value string) error {
			//左边1
			left1Cell := fmt.Sprintf("A%d", rowIndex)
			err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("H%d", rowIndex))
			if err != nil {
				return err
			}
			err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
			if err != nil {
				return err
			}
			b.Excel.SetCellValue(b.SheetName, left1Cell, value)
			return nil
		}
		if b.Content.IsLam {
			drawLeft = func(rowIndex int, value string) error {
				//左边1
				left1Cell := fmt.Sprintf("A%d", rowIndex)
				err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("F%d", rowIndex))
				if err != nil {
					return err
				}
				err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
				if err != nil {
					return err
				}
				b.Excel.SetCellValue(b.SheetName, left1Cell, value)
				return nil
			}

			drawRight = func(rowIndex int, value string) error {
				right1Cell := fmt.Sprintf("G%d", rowIndex)
				err = b.Excel.MergeCell(b.SheetName, right1Cell, fmt.Sprintf("I%d", rowIndex))
				if err != nil {
					return err
				}
				err = b.Excel.SetCellStyle(b.SheetName, right1Cell, right1Cell, styleRight)
				if err != nil {
					return err
				}
				b.Excel.SetCellValue(b.SheetName, right1Cell, value)
				return nil
			}

			drawLall = func(rowIndex int, value string) error {
				//左边1
				left1Cell := fmt.Sprintf("A%d", rowIndex)
				err = b.Excel.MergeCell(b.SheetName, left1Cell, fmt.Sprintf("I%d", rowIndex))
				if err != nil {
					return err
				}
				err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left1Cell, styleLeft)
				if err != nil {
					return err
				}
				b.Excel.SetCellValue(b.SheetName, left1Cell, value)
				return nil
			}

		}
	}

	//第一行
	drawLeft(b.Row, "类别:"+b.Content.Type)
	drawRight(b.Row, "单号:"+b.Content.SerialNumber)
	b.Excel.SetRowHeight(b.SheetName, b.Row, 21)

	//第二行
	drawLeft(b.Row+1, "供应商名称:"+b.Content.Supplier)
	timeformat := b.Content.CreateTime.Local().Format("2006年01月02号 15:04:05")
	drawRight(b.Row+1, "下单时间:"+timeformat)
	b.Excel.SetRowHeight(b.SheetName, b.Row+1, 21)

	//第三行
	drawLeft(b.Row+2, "产品名称:"+b.Content.ProductName)
	status := ""
	if b.Content.Status == "complete" {
		status = "已完成"
	}
	if b.Content.Status == "created" {
		status = "进行中"
	}
	drawRight(b.Row+2, "状态:"+status)
	b.Excel.SetRowHeight(b.SheetName, b.Row+2, 21)

	// 第四行
	drawLall(b.Row+3, "包含工序:"+b.Content.CompProduceName)

	return nil
}

func (b *ProduceBillExcel) drawTableTitle() error {
	b.Row += 4
	var drawCol = func(prefix string, value string) error {
		left1Cell := fmt.Sprintf("%s%d", prefix, b.Row)
		left2Cell := fmt.Sprintf("%s%d", prefix, b.Row+1)

		err := b.Excel.MergeCell(b.SheetName, left1Cell, left2Cell)
		if err != nil {
			return err
		}
		err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left2Cell, b.AlignCenterStyle)
		if err != nil {
			return err
		}

		return b.Excel.SetCellValue(b.SheetName, left1Cell, value)
	}

	var drawCol3 = func(prefix1 string, prefix2 string, value1 string, value2 string, value3 string) error {
		left1Cell := fmt.Sprintf("%s%d", prefix1, b.Row)
		left2Cell := fmt.Sprintf("%s%d", prefix2, b.Row)
		err := b.Excel.MergeCell(b.SheetName, left1Cell, left2Cell)
		if err != nil {
			return err
		}
		if err != nil {
			fmt.Println(err)
			return err
		}
		err = b.Excel.SetCellStyle(b.SheetName, left1Cell, left2Cell, b.AlignCenterStyle)
		if err != nil {
			return err
		}
		b.Excel.SetCellValue(b.SheetName, left1Cell, value1)

		val2Cel := fmt.Sprintf("%s%d", prefix1, b.Row+1)
		b.Excel.SetCellStyle(b.SheetName, val2Cel, val2Cel, b.AlignCenterStyle)
		b.Excel.SetCellValue(b.SheetName, val2Cel, value2)

		val3Cel := fmt.Sprintf("%s%d", prefix2, b.Row+1)
		b.Excel.SetCellStyle(b.SheetName, val3Cel, val3Cel, b.AlignCenterStyle)
		b.Excel.SetCellValue(b.SheetName, val3Cel, value3)
		return nil
	}

	unit := b.Content.Produces[0].Unit
	if b.Content.IsPrint {
		drawCol("A", "加工项目")
		drawCol("B", "规格")
		drawCol("C", "纸张")
		drawCol("D", "来纸尺寸")
		drawCol("E", "来纸数量")
		drawCol("F", "印刷尺寸")
		drawCol("G", "下单数量")
		drawCol("H", "单位")
		drawCol("I", "单价")
		drawCol("J", "预算金额")
		drawCol("K", "交货时间")
		drawCol("L", "备注")

	} else {
		if b.Content.IsLam {
			drawCol("A", "加工项目")
			drawCol("B", "规格")
			drawCol("C", "覆膜尺寸")
			drawCol("D", "下单数量")
			unit2 := b.Content.Produces[0].Unit2
			drawCol3("E", "F", "单价", unit, unit2)
			drawCol("G", "预算金额")
			drawCol("H", "交货时间")
			drawCol("I", "备注")

		} else {
			drawCol("A", "加工项目")
			drawCol("B", "规格")
			drawCol("C", "下单数量")
			drawCol("D", "单位")
			drawCol("E", "单价")
			drawCol("F", "预算金额")
			drawCol("G", "交货时间")
			drawCol("H", "备注")

		}

	}

	return nil
}

func (b *ProduceBillExcel) drawTableContent() error {
	b.Row += 2
	var DrawRow = func(rowIndex int, values ...string) {
		charas := []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"}
		if !b.Content.IsPrint {
			charas = []string{"A", "B", "C", "D", "E", "F", "G", "H"}
			if b.Content.IsLam {
				charas = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I"}
			}
		}

		// }
		for i, c := range charas {
			v := ""
			if i < len(values) {
				v = values[i]
			}
			b.Excel.SetCellValue(b.SheetName, fmt.Sprintf("%s%d", c, rowIndex), v)
			val2Cel := fmt.Sprintf("%s%d", c, rowIndex)
			b.Excel.SetCellStyle(b.SheetName, val2Cel, val2Cel, b.AlignCenterStyle)

			// var magN float64 = 1
			// lenv := len([]rune(v))
			// magN = math.Ceil(float64(lenv) / 10)
			// if lenv%10 > 5 {
			// 	magN = math.Ceil(float64(lenv) / 10)

			// } else {
			// 	n := math.Floor(float64(lenv) / 10)
			// 	if n > 0 {
			// 		magN = n
			// 	}
			// }
			// b.Excel.SetRowHeight(b.SheetName, rowIndex, 21*magN)
			b.Excel.SetRowHeight(b.SheetName, rowIndex, 50)
		}
	}

	produces := b.Content.Produces
	if len(produces) > 0 {
		for _, produce := range produces {
			realCount := ""
			price := produce.OrderPrice
			priceStr := fmt.Sprintf("%.3f", price)
			b.FormatToEmpty(&priceStr)
			// 预算金额
			budgetAmount := fmt.Sprintf("%.3f", produce.OrderPrice*float64(produce.OrderCount))
			b.FormatToEmpty(&budgetAmount)
			// 实际金额
			realPrice := ""
			// 实际完成数
			realCount = fmt.Sprintf("%d", produce.ConfirmCount)
			b.FormatToEmpty(&realCount)
			realPrice = fmt.Sprintf("%.3f", produce.OrderPrice*float64(produce.ConfirmCount))
			b.FormatToEmpty(&realPrice)

			deliveryTime := produce.DeliveryTime.Local().Format("2006-01-02")

			paperCount := fmt.Sprintf("%d", produce.PaperCount)
			b.FormatToEmpty(&paperCount)

			if b.Content.IsPrint {
				DrawRow(b.Row, produce.Name, produce.Norm, produce.Paper, produce.PaperSize, paperCount, produce.PrintSize, fmt.Sprintf("%d", produce.OrderCount), produce.Unit, priceStr, budgetAmount, deliveryTime, produce.Remark)
			} else {
				// 覆膜
				if b.Content.IsLam {
					DrawRow(b.Row, produce.Name, produce.Norm, produce.PrintSize, fmt.Sprintf("%d", produce.OrderCount), priceStr, fmt.Sprintf("%.3f", produce.Price2), budgetAmount, deliveryTime, produce.Remark)
				} else {
					DrawRow(b.Row, produce.Name, produce.Norm, fmt.Sprintf("%d", produce.OrderCount), produce.Unit, priceStr, budgetAmount, deliveryTime, produce.Remark)
				}

			}
			b.Row++
		}
	}

	return nil
}

func (b *ProduceBillExcel) drawTableFooter() error {
	border := []excelize.Border{
		{Type: "top", Style: 1, Color: "000000"},
		{Type: "left", Style: 1, Color: "000000"},
		{Type: "right", Style: 1, Color: "000000"},
		{Type: "bottom", Style: 1, Color: "000000"},
	}

	styleLeft, _ := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "left", Vertical: "center", WrapText: true},
		Border:    border,
	})

	sendToStartCell := fmt.Sprintf("A%d", b.Row)

	sendToEndCell := fmt.Sprintf("I%d", b.Row)
	supplierStartCell := fmt.Sprintf("J%d", b.Row)
	supplierEndCell := fmt.Sprintf("L%d", b.Row)
	if !b.Content.IsPrint {
		sendToEndCell = fmt.Sprintf("E%d", b.Row)
		supplierStartCell = fmt.Sprintf("F%d", b.Row)
		supplierEndCell = fmt.Sprintf("H%d", b.Row)

		if b.Content.IsLam {
			sendToEndCell = fmt.Sprintf("F%d", b.Row)
			supplierStartCell = fmt.Sprintf("G%d", b.Row)
			supplierEndCell = fmt.Sprintf("I%d", b.Row)

		}
	}

	b.Excel.MergeCell(b.SheetName, sendToStartCell, sendToEndCell)
	b.Excel.SetCellStyle(b.SheetName, sendToStartCell, sendToEndCell, styleLeft)
	b.Excel.SetCellValue(b.SheetName, sendToStartCell, "送货地址:"+b.Content.SendTo)
	b.Excel.MergeCell(b.SheetName, supplierStartCell, supplierEndCell)
	b.Excel.SetCellStyle(b.SheetName, supplierStartCell, supplierEndCell, styleLeft)
	b.Excel.SetCellValue(b.SheetName, supplierStartCell, "供应商签字:")
	b.Excel.SetRowHeight(b.SheetName, b.Row, 32)

	return nil
}
func (b *ProduceBillExcel) drawSupplierRemark() error {
	b.Row++
	border := []excelize.Border{
		{Type: "top", Style: 1, Color: "000000"},
		{Type: "left", Style: 1, Color: "000000"},
		{Type: "right", Style: 1, Color: "000000"},
		{Type: "bottom", Style: 1, Color: "000000"},
	}

	styleLeft, _ := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "left", Vertical: "center", WrapText: true},
		Border:    border,
	})

	sendToStartCell := fmt.Sprintf("A%d", b.Row)

	sendToEndCell := fmt.Sprintf("L%d", b.Row)
	if !b.Content.IsPrint {
		sendToEndCell = fmt.Sprintf("H%d", b.Row)

		if b.Content.IsLam {
			sendToEndCell = fmt.Sprintf("I%d", b.Row)

		}
	}

	b.Excel.MergeCell(b.SheetName, sendToStartCell, sendToEndCell)
	b.Excel.SetCellStyle(b.SheetName, sendToStartCell, sendToEndCell, styleLeft)
	b.Excel.SetCellValue(b.SheetName, sendToStartCell, "供应商备注:"+b.Content.SupplierRemark)
	b.Excel.SetRowHeight(b.SheetName, b.Row, 32)
	return nil

}

func (b *ProduceBillExcel) drawTableSignature() error {
	b.Row += 2

	style1, _ := b.Excel.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center"},
		// Border:    border,
	})

	// 制单人
	billUserCellS := fmt.Sprintf("A%d", b.Row+1)
	billUserCellE := fmt.Sprintf("B%d", b.Row+1)
	b.Excel.MergeCell(b.SheetName, billUserCellS, billUserCellE)
	b.Excel.SetCellValue(b.SheetName, billUserCellS, "制单人:"+b.Content.UserName)

	fontNum := "G"
	fontENum := "H"
	image1s := "I"
	image2s := "K"
	image1e := "J"
	image2e := "L"
	if !b.Content.IsPrint {
		fontNum = "E"
		fontENum = "E"
		image1s = "F"
		image2s = "H"
		image1e = "G"
		image2e = "H"
		if b.Content.IsLam {
			fontNum = "E"
			fontENum = "E"
			image1s = "F"
			image2s = "H"
			image1e = "G"
			image2e = "I"

		}
	}

	fontCell := fmt.Sprintf("%s%d", fontNum, b.Row)
	fontEndCell := fmt.Sprintf("%s%d", fontENum, b.Row+2)

	imageCell1 := fmt.Sprintf("%s%d", image1s, b.Row)
	imageEndCell1 := fmt.Sprintf("%s%d", image1e, b.Row+2)

	imageCell2 := fmt.Sprintf("%s%d", image2s, b.Row)
	imageEndCell2 := fmt.Sprintf("%s%d", image2e, b.Row+2)

	b.Excel.MergeCell(b.SheetName, fontCell, fontEndCell)
	b.Excel.SetCellStyle(b.SheetName, fontCell, fontCell, style1)
	b.Excel.SetCellValue(b.SheetName, fontCell, "审核签字:")

	// 签字图片1 I10-J12
	b.Excel.MergeCell(b.SheetName, imageCell1, imageEndCell1)
	b.Excel.SetCellStyle(b.SheetName, imageCell1, imageCell1, style1)
	b.Excel.SetCellValue(b.SheetName, imageCell1, "")

	// 签字图片2 K10-L12
	b.Excel.MergeCell(b.SheetName, imageCell2, imageEndCell2)
	b.Excel.SetCellStyle(b.SheetName, imageCell2, imageCell1, style1)
	b.Excel.SetCellValue(b.SheetName, imageCell2, "")

	// 状态为已审核时,签字
	if b.Content.Reviewed == 1 {
		imageCells := []string{imageCell1, imageCell2}
		if len(b.Signatures) > 0 {
			for k, sign := range b.Signatures {
				b.Excel.AddPicture(b.SheetName, imageCells[k], sign.Path, sign.Format)

			}
		}
	}

	b.Excel.SetRowHeight(b.SheetName, b.Row, 21)

	return nil
}

func (b *ProduceBillExcel) Draws() {
	b.drawTitle()
	b.drawSubTitles()
	b.drawTableTitle()
	b.drawTableContent()
	b.drawTableFooter()
	if len(b.Content.SupplierRemark) > 1 {
		b.drawSupplierRemark()

	}
	b.drawTableSignature()
}

func NewProduceBill(f *excelize.File) *ProduceBillExcel {

	border := []excelize.Border{
		{Type: "top", Style: 1, Color: "000000"},
		{Type: "left", Style: 1, Color: "000000"},
		{Type: "right", Style: 1, Color: "000000"},
		{Type: "bottom", Style: 1, Color: "000000"},
	}

	styleLeft, _ := f.NewStyle(&excelize.Style{
		Alignment: &excelize.Alignment{Horizontal: "center", Vertical: "center", WrapText: true},
		Border:    border,
	})

	b := &ProduceBillExcel{
		Title:            "中鱼互动加工单",
		SheetName:        "Sheet1",
		Excel:            f,
		Offset:           0,
		AlignCenterStyle: styleLeft,
		Signatures:       make([]*model.Signature, 0),
	}

	f.SetPageMargins(b.SheetName, excelize.PageMarginTop(1), excelize.PageMarginLeft(0), excelize.PageMarginRight(0))

	return b
}

func (b *ProduceBillExcel) FormatToEmpty(str *string) {
	if *str == "0" || *str == "0.000" {
		*str = "-"
	}

}

func (b *ProduceBillExcel) SetContent(content interface{}) {
	b.Content = content.(*model.ProduceBill)

}
func (b *ProduceBillExcel) SetTitle(title string) {
	b.Title = title

}

func (b *ProduceBillExcel) SetSheetName(name string) {
	b.SheetName = name

}
func (b *ProduceBillExcel) SetRow(row int) {
	b.Row = row
}

func (b *ProduceBillExcel) SetIsPdf(isPdf string) {
	b.IsPdf = isPdf
}
func (b *ProduceBillExcel) GetRow() int {
	return b.Row
}

func (b *ProduceBillExcel) SetSignatures(sign interface{}) {
	b.Signatures = sign.([]*model.Signature)

}