package demo

import (
	"ciyon/web/admin"
	c "ciyon/zciyon"
	"ciyon/zciyon/xlsx"
	"fmt"
	"math/rand"
	"net/http"
	"regexp"
	"strconv"
	"strings"
)

func normal_setwhere(post *c.CiyPost) (map[string]any, *c.CiySQL) {
	ret := map[string]any{}
	query := post.Getobj("query")
	csql := c.NewCiySQL("demo_normal")
	liid := c.Getint(query, "liid")
	if liid > 0 {
		csql.Where("auditstatus", liid)
	}
	csql.Where_daterange("audittimes", c.Getstr(query, "audittimes"))
	csql.Where("name like", c.Getstr(query, "name"))
	val := c.Getstr(query, "menuid")
	if val != "" {
		csqlt := c.NewCiySQL("zc_menu")
		csqlt.Where("name like", val)
		trow, _ := c.CiyDB.Getone(csqlt)
		if trow != nil {
			csql.Where("menuid", trow["id"])
			ret["menuid"] = trow["name"]
		} else {
			csql.Where("menuid=0")
		}
	}
	csql.Where_numrange("bankmoney", c.Getstr(query, "bankmoney_1"), c.Getstr(query, "bankmoney_2"), 1000000)
	csql.Where("isopen", c.Getstr(query, "isopen"))
	csql.Where("mauditstatus like", c.Getstr(query, "mauditstatus"))
	valint := c.Getint(query, "renzheng")
	if valint > 0 {
		valint = 1 << (valint - 1)
		csql.Where(fmt.Sprintf("renzheng&%d=%d", valint, valint))
	}
	order := c.Getstr(query, "order", "id desc")
	csql.Order(order)
	query["order"] = order
	return query, csql
}
func Normal_list(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	where, csql := normal_setwhere(post)
	csql.Column("!content")
	pageno := post.Getint("pageno", 1)
	pagecount := post.Getint("pagecount", 10)
	csql.Limit(pageno, pagecount)
	rows, mainrowcount, err := c.CiyDB.Get(csql, post.Getint("count"))
	if err != nil {
		return c.ErrJSON(w, "读取错误", err)
	}
	ret := map[string]any{}
	ret["where"] = where
	ret["pageno"] = pageno
	ret["pagecount"] = pagecount
	ret["count"] = mainrowcount
	ret["list"] = rows
	if post.Getbool("field") {
		field, fshow := c.CiyDB.GetField(csql)
		c.FieldAdd(&field, &fshow, 0, "_btn", "操作")
		ret["fshow"] = fshow
		ret["field"] = field
	}
	if post.Getbool("once") {
		once := map[string]any{}
		input := make([]map[string]any, 0)
		input = append(input, map[string]any{
			"form":   "liid",
			"type":   "select",
			"name":   "",
			"select": "auditstatus",
			"all":    "全部",
		})
		input = append(input, map[string]any{
			"form": "audittimes",
			"type": "daterange",
			"name": "审核时间",
		})
		input = append(input, map[string]any{
			"form": "name",
			"type": "input",
			"name": "默认标题",
			"prop": ` style="width:8em;"`,
		})
		input = append(input, map[string]any{
			"form": "menuid",
			"type": "input",
			"name": "所属菜单",
			"prop": ` style="width:8em;"`,
		})
		input = append(input, map[string]any{
			"form": "bankmoney",
			"type": "num",
			"name": "贷款金额",
			"prop": ` style="width:4em;"`,
		})
		input = append(input, map[string]any{
			"form":   "isopen",
			"type":   "select",
			"name":   "是否开启",
			"select": c.CiyDB.Getdbcodes("demo_normal", "isopen"),
			"all":    "全部",
		})
		input = append(input, map[string]any{
			"form":   "mauditstatus",
			"type":   "select",
			"name":   "多选状态",
			"select": "auditstatus",
			"all":    "全部",
		})
		input = append(input, map[string]any{
			"form":   "renzheng",
			"type":   "select",
			"name":   "认证情况",
			"select": "renzheng",
			"all":    "全部",
		})
		orders := make([]map[string]any, 0)
		orders = append(orders, map[string]any{
			"id":   "id desc",
			"name": "默认排序",
		})
		orders = append(orders, map[string]any{
			"id":   "audittimes desc",
			"name": "审核时间排序",
		})
		orders = append(orders, map[string]any{
			"id":   "bankmoney",
			"name": "贷款金额小到大",
		})
		orders = append(orders, map[string]any{
			"id":   "bankmoney desc",
			"name": "贷款金额大到小",
		})
		input = append(input, map[string]any{
			"form":   "order",
			"type":   "select",
			"name":   "排序",
			"select": orders,
		})
		once["input"] = input
		once["renzheng"] = c.CiyDB.Getdbcodes("demo_normal", "renzheng")
		// csql = c.NewCiySQL("zc_menu")
		// csql.Column("id,name")
		// once["zc_menu"], _, _ = c.CiyDB.Get(csql)
		ret["once"] = once
	}
	ret["zc_menu"] = c.Getrelation(c.CiyDB, rows, "zc_menu", "menuid", map[string]string{"column": "id,name"}, map[string]string{"queryid": "id"})
	return c.SuccJSON(w, r, ret)
}
func Normal_getdata(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, _userid := admin.Verifyfast(r, c.CiyDB, post)
	if _userid == 0 {
		return false
	}
	id := post.Getint("id")
	ret := map[string]any{}
	csql := c.NewCiySQL("demo_normal")
	csql.Where("id", id)
	datarow, _ := c.CiyDB.Getone(csql)
	if datarow == nil {
		datarow = map[string]any{}
	}
	ret["data"] = datarow
	if post.Get("act") == "edit" {
		csql = c.NewCiySQL("zc_menu")
		csql.Column("id,name")
		menurows, _, _ := c.CiyDB.Get(csql)
		ret["zc_menu"] = menurows
	}
	return c.SuccJSON(w, r, ret)
}
func Normal_update(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, _userid := admin.Verifyfast(r, c.CiyDB, post)
	if _userid == 0 {
		return false
	}
	// if admin.Nopower(c.CiyDB, _userid, "p u") {
	// 	return c.ErrJSON(w, "您未被授权操作")
	// }
	var err error
	id := post.Getint("id")
	name := post.Get("name")
	menuid := post.Getint("menuid")
	filesize := post.Getint("filesize")
	metre := post.Getint("metre")
	bankmoney := post.Getint("bankmoney")
	setdate := post.Getint("setdate")
	settimes := post.Getint("settimes")
	downurl := post.Get("downurl")
	avar := post.Get("avar")
	isuse := post.Getint("isuse")
	isopen := post.Getint("isopen")
	unit := post.Get("unit")
	sigstatus := post.Getint("sigstatus")
	mauditstatus := post.Get("mauditstatus")
	prodcata := post.Getint("prodcata")
	areacode := post.Getint("areacode")
	renzheng := post.Getint("renzheng")
	npcyc := post.Getint("npcyc")
	runsec := post.Getint("runsec")
	acttm := post.Getint("acttm")
	imgs := post.Get("imgs")
	ton := post.Getint("ton")
	price := post.Getint("price")
	lat := post.Getint("lat")
	lng := post.Getint("lng")
	url := post.Get("url")
	idcard := post.Get("idcard")
	weightg := post.Getint("weightg")
	eartmpr := post.Getint("eartmpr")
	content := post.Get("content")
	md := post.Get("md")
	if name == "" {
		return c.ErrJSON(w, "请填写默认标题")
	}
	var datarow map[string]any
	if id > 0 {
		csql := c.NewCiySQL("demo_normal")
		csql.Where("id", id)
		datarow, err = c.CiyDB.Getone(csql)
		if err != nil {
			return c.ErrJSON(w, "读取数据失败", err)
		}
		if datarow == nil {
			return c.ErrJSON(w, "数据不存在")
		}
	}

	var updata = map[string]any{}
	err = c.CiyDB.Tran(func() error {
		csql := c.NewCiySQL("demo_normal")
		csql.Where("name", name)
		csql.Column("id")
		chkid := c.Toint(c.CiyDB.Get1(csql))
		if chkid > 0 && ((id > 0 && chkid != id) || id == 0) {
			return fmt.Errorf("数据已存在")
		}
		updata["name"] = name
		updata["menuid"] = menuid
		updata["filesize"] = filesize
		updata["metre"] = metre
		updata["bankmoney"] = bankmoney
		updata["setdate"] = setdate
		updata["settimes"] = settimes
		updata["downurl"] = downurl
		updata["avar"] = avar
		updata["isuse"] = isuse
		updata["isopen"] = isopen
		updata["unit"] = unit
		updata["sigstatus"] = sigstatus
		updata["mauditstatus"] = mauditstatus
		updata["prodcata"] = prodcata
		updata["areacode"] = areacode
		updata["renzheng"] = renzheng
		updata["npcyc"] = npcyc
		updata["runsec"] = runsec
		updata["acttm"] = acttm
		updata["imgs"] = imgs
		updata["ton"] = ton
		updata["price"] = price
		updata["lat"] = lat
		updata["lng"] = lng
		updata["url"] = url
		updata["idcard"] = idcard
		updata["weightg"] = weightg
		updata["eartmpr"] = eartmpr
		updata["content"] = content
		updata["md"] = md
		csql = c.NewCiySQL("demo_normal")
		if id > 0 {
			csql.Where("id", id)
			_, err = c.CiyDB.Update(csql, updata)
		} else {
			updata["auditstatus"] = 20
			updata["addtimes"] = c.Tostamp()
			id, err = c.CiyDB.Insert(csql, updata)
		}
		updata["id"] = id
		if err != nil {
			return fmt.Errorf("更新失败:%v", err)
		}
		admin.SaveLogDB(c.CiyDB, "demo_normal", datarow, updata)
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, err.Error())
	}
	ret := map[string]any{}
	ret["data"] = updata
	return c.SuccJSON(w, r, ret)
}

func Normal_audit(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	// if admin.Nopower(c.CiyDB, userid, "p d") {
	// 	return c.ErrJSON(w, "您未被授权操作")
	// }
	ids := post.Get("ids")
	auditstatus := post.Getint("auditstatus")
	auditmsg := post.Get("auditmsg")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	if auditstatus == 90 && auditmsg == "" {
		return c.ErrJSON(w, "请填写驳回原因")
	}
	csql := c.NewCiySQL("demo_normal")
	csql.Where("id in", ids)
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取数据错误", err)
	}
	vids := make([]int, 0)
	var updata = map[string]any{}
	err = c.CiyDB.Tran(func() error {
		for _, row := range rows {
			updata["auditstatus"] = auditstatus
			updata["audituser"] = userid
			updata["audittimes"] = c.Tostamp()
			updata["auditmsg"] = auditmsg
			csql = c.NewCiySQL("demo_normal")
			csql.Where("id", row["id"])
			_, err = c.CiyDB.Update(csql, updata)
			if err != nil {
				return fmt.Errorf("审核失败:%v", err)
			}
			vids = append(vids, c.Toint(row["id"]))
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, err.Error())
	}
	ret := map[string]any{}
	ret["data"] = updata
	ret["ids"] = vids
	return c.SuccJSON(w, r, ret)
}
func Normal_del(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	// if admin.Nopower(c.CiyDB, userid, "p d") {
	// 	return c.ErrJSON(w, "您未被授权操作")
	// }
	ids := post.Get("ids")
	if ids == "" {
		return c.ErrJSON(w, "请选择至少一条")
	}
	csql := c.NewCiySQL("demo_normal")
	csql.Where("id in", ids)
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取数据错误", err)
	}
	vids := make([]int, 0)
	err = c.CiyDB.Tran(func() error {
		for _, row := range rows {
			delid := c.Toint(row["id"])
			//c.Delcheck(c.CiyDB, delid, "tablexx", "xxid", "xxx");
			//c.Delall(c.CiyDB, delid, "tablexx", "xxid", "xxx");
			c.Delme(c.CiyDB, delid, "demo_normal")
			admin.SaveLogDB(c.CiyDB, "demo_normal", row, nil)
			vids = append(vids, delid)
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, "事务"+err.Error())
	}
	ret := map[string]any{}
	ret["ids"] = vids
	return c.SuccJSON(w, r, ret)
}

func Normal_exportxls(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	// if admin.Nopower(c.CiyDB, userid, "p00e") {
	// 	return c.ErrJSON(w, "您未被授权操作")
	// }
	_, csql := normal_setwhere(post)
	rows, _, err := c.CiyDB.Get(csql)
	if err != nil {
		return c.ErrJSON(w, "读取错误", err)
	}
	if len(rows) > 10000 {
		return c.ErrJSON(w, "将导出"+c.Tostr(len(rows))+"条，不建议超过1万条，请筛选缩小范围", err)
	}
	fields := []map[string]string{}
	fields = append(fields, map[string]string{"style": "c", "width": "60", "field": "id", "name": "行码"})
	fields = append(fields, map[string]string{"style": "c", "width": "100", "field": "auditstatus", "name": "审核状态"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "audituser", "name": "审核人"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "audittimes", "name": "审核时间"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "name", "name": "默认标题"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "menuid", "name": "所属菜单"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "filesize", "name": "文件大小"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "metre", "name": "长度"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "bankmoney", "name": "贷款金额"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "setdate", "name": "设置日期"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "settimes", "name": "设置时间"})
	fields = append(fields, map[string]string{"style": "c", "width": "100", "field": "isuse", "name": "是否使用"})
	fields = append(fields, map[string]string{"style": "c", "width": "100", "field": "isopen", "name": "是否开启"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "unit", "name": "库存单位"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "sigstatus", "name": "单选状态"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "mauditstatus", "name": "多选状态"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "prodcata", "name": "商品分类"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "areacode", "name": "所在地区"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "renzheng", "name": "认证情况"})
	fields = append(fields, map[string]string{"style": "c", "width": "100", "field": "npcyc", "name": "执行周期"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "runsec", "name": "执行用时"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "acttm", "name": "活动期数"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "ton", "name": "吨位"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "price", "name": "单价"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "lat", "name": "纬度"})
	fields = append(fields, map[string]string{"style": "c", "width": "100", "field": "lng", "name": "位置"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "url", "name": "链接"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "idcard", "name": "身份证号"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "weightg", "name": "体重"})
	fields = append(fields, map[string]string{"style": "r", "width": "100", "field": "eartmpr", "name": "耳温"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "content", "name": "介绍"})
	fields = append(fields, map[string]string{"style": "l", "width": "100", "field": "addtimes", "name": "添加时间"})

	code_auditstatus := admin.Getcatas(c.CiyDB, "auditstatus")
	code_audituser := c.Getrelation(c.CiyDB, rows, "xa_user", "audituser")
	code_menuid, _, _ := c.CiyDB.Get(c.NewCiySQL("zc_menu").Column("id,name"))
	code_isuse := c.CiyDB.Getdbcodes("demo_normal", "isuse")
	code_isopen := c.CiyDB.Getdbcodes("demo_normal", "isopen")
	code_mauditstatus := admin.Getcatas(c.CiyDB, "auditstatus")
	code_prodcata := admin.Getcatas(c.CiyDB, "prodcata")
	code_areacode, _, _ := c.CiyDB.Get(c.NewCiySQL("ciy_arearpc").Column("id,name,upid"))
	code_renzheng := admin.Getcatas(c.CiyDB, "renzheng")

	datas := [][]string{}
	for _, row := range rows {
		dat := make([]string, 0)
		for _, f := range fields {
			field := f["field"]
			if val, ok := row[field]; ok {
				var str string
				if field == "id" {
					str = c.EnID(c.Toint(val))
				} else if field == "auditstatus" {
					str = c.Ccode(code_auditstatus, c.Toint(val))
				} else if field == "audituser" {
					str = c.Ccode(code_audituser, c.Toint(val))
				} else if field == "audittimes" {
					str = c.Iff(c.Toint(val) > 0, c.Todate(c.Toint(val), "Y-m-d H:i"), "--")
				} else if field == "menuid" {
					str = c.Ccode(code_menuid, c.Toint(val))
				} else if field == "metre" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.2f", c.Tofloat(val)/1000), "--")
				} else if field == "bankmoney" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.3f", c.Tofloat(val)/1000000), "--")
				} else if field == "setdate" {
					str = c.Iff(c.Toint(val) > 0, c.Todate(c.Toint(val), "Y-m-d H:i"), "--")
				} else if field == "settimes" {
					str = c.Iff(c.Toint(val) > 0, c.Todate(c.Toint(val), "Y-m-d H:i"), "--")
				} else if field == "isuse" {
					str = c.Iff(c.Toint(val) == 0, c.Tostr(code_isuse[0]["name"]), c.Tostr(code_isuse[1]["name"]))
				} else if field == "isopen" {
					str = c.Iff(c.Toint(val) == 0, c.Tostr(code_isopen[0]["name"]), c.Tostr(code_isopen[1]["name"]))
				} else if field == "sigstatus" {
					str = c.Ccode(code_auditstatus, c.Toint(val))
				} else if field == "mauditstatus" {
					str = strings.Join(c.Scode(code_mauditstatus, c.Tostr(val)), ",")
				} else if field == "prodcata" {
					str = strings.Join(c.Mcode(code_prodcata, c.Toint(val)), "-")
				} else if field == "areacode" {
					str = strings.Join(c.Mcode(code_areacode, c.Toint(val)), "-")
				} else if field == "renzheng" {
					number := c.Toint(val)
					strs := make([]string, 0)
					for _, cod := range code_renzheng {
						if number&(1<<uint(c.Toint(cod["id"])-1)) != 0 {
							strs = append(strs, c.Tostr(cod["name"]))
						}
					}
					str = strings.Join(strs, ",")
				} else if field == "npcyc" {
					va := c.Toint(val)
					if va < 0 {
						str = c.Tostr(-va) + "月"
					} else if va >= 86400 {
						str = c.Tostr(c.Toint(va/86400)) + "天"
					} else {
						str = c.Tostr(va) + "秒"
					}
				} else if field == "unit" {
					us := strings.Split(c.Tostr(val), "|")
					str = ""
					if len(us) == 5 {
						str = "1" + us[4] + us[3] + us[2] + ","
					}
					if len(us) > 2 {
						str += "1" + us[2] + us[1] + us[0]
					}
					if str == "" && len(us) > 0 {
						str = us[0]
					}
				} else if field == "ton" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.2f", c.Tofloat(val)/1000000), "--")
				} else if field == "price" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.2f", c.Tofloat(val)/100), "--")
				} else if field == "weightg" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.2f", c.Tofloat(val)/1000), "--")
				} else if field == "eartmpr" {
					str = c.Iff(c.Toint(val) > 0, fmt.Sprintf("%.1f", c.Tofloat(val)/1000), "--")
				} else if field == "addtimes" {
					str = c.Iff(c.Toint(val) > 0, c.Todate(c.Toint(val), "Y-m-d H:i"), "--")
				} else {
					str = c.Tostr(val)
				}
				dat = append(dat, str)
			} else {
				dat = append(dat, "")
			}
		}
		datas = append(datas, dat)
	}
	param := map[string]any{}
	total := []map[string]any{}
	param["field"] = fields
	param["data"] = datas
	param["sheetname"] = "数据报表"
	param["titleheight"] = "25" //列头高度
	param["landscape"] = true   //横向打印
	param["fixtopage"] = true   //打印整个工作表
	param["toptitle"] = "Demo数据报表"
	str := c.General_excel_xml(fields, datas, param, total)
	filename := "/ud/tmp/" + c.Todate(-1, "Ymd_His") + c.Tostr(rand.Intn(8999)+1000) + ".xls"
	err = c.FileSave(c.CiyWebDir+filename, str)
	if err != nil {
		return c.ErrJSON(w, "导出保存文件错误:%v[%v]", err, filename)
	}
	ret := map[string]any{}
	ret["url"] = filename
	return c.SuccJSON(w, r, ret)
}
func Normal_importxls_in(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	// if admin.Nopower(c.CiyDB, userid, "p00e") {
	// 	return c.ErrJSON(w, "您未被授权操作")
	// }
	file := post.Get("file")
	if c.FileExist(c.CiyWebDir+file) != nil {
		return c.ErrJSON(w, "文件不存在")
	}

	//github.com/qax-os/excelize
	//github.com/xuri/excelize
	// github.com/extrame/xls
	//只支持xlsx格式，其他ole2/xml等格式需使用导入其他依赖库
	xlFile, err := xlsx.OpenFile(c.CiyWebDir + file)
	if err != nil {
		return c.ErrJSON(w, "文件打开错误:%v", err)
	}
	datas, err := xlFile.ToSlice()
	if err != nil {
		return c.ErrJSON(w, "文件解析错误:%v", err)
	}
	datacnt := len(datas[0])
	if datacnt < 2 {
		return c.ErrJSON(w, "数据为空")
	}
	html := ""
	headsn := []string{}
	headsn = append(headsn, "行码.id")
	headsn = append(headsn, "审核状态.auditstatus")
	headsn = append(headsn, "审核人.audituser")
	headsn = append(headsn, "审核时间.audittimes")
	headsn = append(headsn, "默认标题.name")
	headsn = append(headsn, "所属菜单.menuid")
	headsn = append(headsn, "文件大小.filesize")
	headsn = append(headsn, "长度.metre")
	headsn = append(headsn, "贷款金额.bankmoney")
	headsn = append(headsn, "设置日期.setdate")
	headsn = append(headsn, "设置时间.settimes")
	headsn = append(headsn, "是否使用.isuse")
	headsn = append(headsn, "是否开启.isopen")
	headsn = append(headsn, "库存单位.unit")
	headsn = append(headsn, "单选状态.sigstatus")
	headsn = append(headsn, "多选状态.mauditstatus")
	headsn = append(headsn, "商品分类.prodcata")
	headsn = append(headsn, "所在地区.areacode")
	headsn = append(headsn, "认证情况.renzheng")
	headsn = append(headsn, "执行周期.npcyc")
	headsn = append(headsn, "执行用时.runsec")
	headsn = append(headsn, "活动期数.acttm")
	headsn = append(headsn, "吨位.ton")
	headsn = append(headsn, "单价.price")
	headsn = append(headsn, "纬度.lat")
	headsn = append(headsn, "位置.lng")
	headsn = append(headsn, "链接.url")
	headsn = append(headsn, "身份证号.idcard")
	headsn = append(headsn, "体重.weightg")
	headsn = append(headsn, "耳温.eartmpr")
	headsn = append(headsn, "介绍.content")

	xlsidx := 1
	if datas[0][0][len(headsn)-1] == "" {
		xlsidx = 2
	}
	heads := make([]map[string]string, 0)
	for _, head := range headsn {
		hd := strings.Split(head, ".")
		if len(hd) < 2 {
			continue
		}
		heads = append(heads, map[string]string{
			"idx":  c.Tostr(c.In_array(datas[0][xlsidx-1], hd[0])),
			"fld":  hd[1],
			"name": hd[0],
		})
	}

	code_auditstatus := admin.Getcatas(c.CiyDB, "auditstatus")
	code_userid, _, _ := c.CiyDB.Get(c.NewCiySQL("xa_user").Column("id,name"))
	code_menuid, _, _ := c.CiyDB.Get(c.NewCiySQL("zc_menu").Column("id,name"))
	code_isuse := c.CiyDB.Getdbcodes("demo_normal", "isuse")
	code_isopen := c.CiyDB.Getdbcodes("demo_normal", "isopen")
	code_mauditstatus := admin.Getcatas(c.CiyDB, "auditstatus")
	code_prodcata := admin.Getcatas(c.CiyDB, "prodcata")
	code_areacode, _, _ := c.CiyDB.Get(c.NewCiySQL("ciy_arearpc").Column("id,name,upid"))
	code_renzheng := admin.Getcatas(c.CiyDB, "renzheng")

	html += "<div class=\"table\">\n"
	html += "<table><thead><tr>\n"
	html += "<th>#</th>\n"
	for _, arr := range heads {
		html += "<th>" + arr["name"] + "</th>\n"
	}
	html += "</tr>\n"
	cnt := 0
	uniques := make(map[string]any)
	id := 0
	for rowidx := xlsidx; rowidx < datacnt; rowidx++ {
		lineidx := c.Tostr(rowidx - xlsidx + 1)
		hrhtml := ""
		firsthtml := "<td><div>" + lineidx + "</div></td>"
		bempty := true
		unqs := make([]string, 0)
		csql := c.NewCiySQL("demo_normal")
		for _, arr := range heads {
			name := arr["name"]
			errmsg := ""  //数据有误，显示红色说明
			showdat := "" //显示在表格中的数据
			if c.Toint(arr["idx"]) > -1 {
				showdat = strings.TrimSpace(datas[0][rowidx][c.Toint(arr["idx"])])
			}
			if showdat == "--" {
				showdat = ""
			}
			var value any
			value = showdat //在表单中的数据(转换后)
			ext := ""       //扩展表单
			if name == "行码" {
				if showdat == "" {
					value = 0
					showdat = "<kbd>新增</kbd>"
				} else {
					id = c.DeID(showdat)
					if id == 0 {
						errmsg = name + "解析错误"
					} else {
						csqlchk := c.NewCiySQL("demo_normal")
						csqlchk.Where("id", id).Column("id")
						chkid := c.Toint(c.CiyDB.Get1(csqlchk))
						if chkid != id {
							errmsg = name + "在数据库中不存在"
						}
						value = id
					}
				}
			} else if name == "审核状态" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Dcode(code_auditstatus, c.Tostr(showdat))
					if value == -1 {
						errmsg = name + "文字与系统数据不匹配"
					}
				}
			} else if name == "审核人" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Dcode(code_userid, showdat)
					if value == -1 {
						errmsg = name + "文字与系统数据不匹配"
					}
				}
			} else if name == "审核时间" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Tostamp(c.Tostr(showdat))
					if value == 0 {
						errmsg = name + "时间格式错误"
					} else {
						showdat = c.Todate(c.Toint(value), "Y-m-d H:i:s")
					}
				}
			} else if name == "默认标题" {
				if showdat == "" {
					errmsg = name + "为必填项"
				} else {
					csql.Where("name", showdat)
					unqs = append(unqs, showdat)
				}
			} else if name == "所属菜单" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Dcode(code_menuid, showdat)
					if value == -1 {
						errmsg = name + "文字与系统数据不匹配"
					}
				}
			} else if name == "文件大小" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.Atoi(showdat)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "长度" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 1000)
						showdat += "米"
					}
				}
			} else if name == "贷款金额" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 1000000)
						showdat += "万元"
					}
				}
			} else if name == "设置日期" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Tostamp(c.Tostr(showdat))
					if value == 0 {
						errmsg = name + "时间格式错误"
					} else {
						showdat = c.Todate(c.Toint(value), "Y-m-d")
					}
				}
			} else if name == "设置时间" {
				if showdat == "" {
					value = 0
				} else {
					value = c.Tostamp(c.Tostr(showdat))
					if value == 0 {
						errmsg = name + "时间格式错误"
					} else {
						showdat = c.Todate(c.Toint(value), "Y-m-d H:i:s")
					}
				}
			} else if name == "是否使用" {
				if showdat == "" {
					value = 0
				} else {
					if showdat == code_isuse[0]["name"] {
						value = 1
						showdat = c.Tostr(code_isuse[0]["name"])
					} else {
						value = 2
						showdat = c.Tostr(code_isuse[1]["name"])
					}
				}
			} else if name == "是否开启" {
				if showdat == "" {
					value = 0
				} else {
					if showdat == code_isopen[0]["name"] {
						value = 1
						showdat = c.Tostr(code_isuse[0]["name"])
					} else {
						value = 2
						showdat = c.Tostr(code_isuse[1]["name"])
					}
				}
			} else if name == "库存单位" {
				//显示   1箱=5盒,1盒=10袋     存储  袋|10|盒|5|箱
				if showdat == "" {
				} else {
					us := strings.Split(showdat, ",")
					if len(us) == 2 {
						tmp := us[0]
						us[0] = us[1]
						us[1] = tmp
					}
					us[0] = us[0][1:]
					re := regexp.MustCompile(`(.*?)(\d+)(.*)`)
					matches := re.FindStringSubmatch(us[0])
					if len(matches) >= 4 {
						unitx := matches[1]
						value = matches[3] + "|" + matches[2] + "|" + matches[1]
						if len(us) == 2 {
							us[1] = us[1][1:]
							matches = re.FindStringSubmatch(us[1])
							if len(matches) >= 4 {
								if unitx != matches[3] {
									errmsg = name + "中间单位不匹配"
								} else {
									value = c.Tostr(value) + "|" + matches[2] + "|" + matches[1]
								}
							} else {
								errmsg = name + "第二段格式错误"
							}
						}
					} else {
						errmsg = name + "第一段格式错误"
					}
				}
			} else if name == "多选状态" {
				if showdat == "" {
				} else {
					tdats := strings.Split(showdat, ",")
					vals := make([]string, 0)
					for _, da := range tdats {
						tval := c.Dcode(code_mauditstatus, da)
						if tval == -1 {
							errmsg = name + "文字与系统数据不匹配"
						}
						vals = append(vals, c.Tostr(tval))
					}
					value = strings.Join(vals, ",")
				}
			} else if name == "商品分类" {
				if showdat == "" {
					value = 0
				} else {
					dats := strings.Split(showdat, "-")
					value = c.Dcode(code_prodcata, dats[len(dats)-1])
					if value == -1 {
						errmsg = name + "文字与系统数据不匹配"
					}
				}
			} else if name == "所在地区" {
				if showdat == "" {
					value = 0
				} else {
					dats := strings.Split(showdat, "-")
					value = c.Dcode(code_areacode, dats[len(dats)-1])
					if value == -1 {
						errmsg = name + "文字与系统数据不匹配"
					}
				}
			} else if name == "认证情况" {
				if showdat == "" {
					value = 0
				} else {
					dats := strings.Split(showdat, ",")
					tdat := 0
					for _, da := range dats {
						bti := c.Dcode(code_renzheng, da)
						if bti == -1 {
							errmsg = name + "文字与系统数据不匹配"
						}
						tdat += (1 << (bti - 1))
					}
					value = tdat
				}
			} else if name == "执行周期" {
				if showdat == "" {
					value = 0
				} else {
					last := showdat[len(showdat)-3:]
					dd := c.Toint(showdat[:len(showdat)-3])
					if dd == 0 {
						errmsg = name + "周期数字错误"
					} else if last == "天" {
						value = dd * 86400
					} else if last == "月" {
						value = -dd
					} else if last == "秒" {
						value = dd
					} else {
						errmsg = name + "周期单位错误"
					}
				}
			} else if name == "执行用时" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.Atoi(showdat)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "活动期数" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.Atoi(showdat)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "吨位" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 1000000)
						showdat += "吨"
					}
				}
			} else if name == "单价" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 100)
						showdat += "元"
					}
				}
			} else if name == "纬度" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "位置" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "监管数量" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = idat
					}
				}
			} else if name == "链接" {
			} else if name == "身份证号" {
			} else if name == "体重" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 1000)
						showdat += "KG"
					}
				}
			} else if name == "耳温" {
				if showdat == "" {
					value = 0
				} else {
					idat, err := strconv.ParseFloat(showdat, 64)
					if err != nil {
						errmsg = name + "不是数字"
					} else {
						value = c.Toint(idat * 1000)
						showdat += "℃"
					}
				}
			} else if name == "介绍" {
			}
			if showdat != "" {
				bempty = false
			}
			if errmsg == "" {
				hrhtml += "<td><div>" + showdat + "<input type=\"hidden\" name=\"" + c.Tostr(arr["fld"]) + "_" + lineidx + "\" value=\"" + c.Tostr(value) + "\"/>" + ext + "</div></td>"
			} else {
				hrhtml += "<td><div style=\"background:#ffe8c5;\" title=\"#" + lineidx + ":" + errmsg + "\">" + showdat + "</div></td>"
			}
		}
		if bempty {
			continue
		}

		if len(unqs) > 0 {
			unq := strings.Join(unqs, "|")
			if _, ok := uniques[unq]; ok {
				firsthtml = "<td style=\"background:#ffe8c5;\" title=\"#" + lineidx + ":该行与待导入数据有重复\"><div class=\"lang\">重复</div></td>"
			} else {
				uniques[unq] = true
				csql.Column("id")
				chkid := c.Toint(c.CiyDB.Get1(csql))
				if chkid > 0 && ((id > 0 && chkid != id) || id == 0) {
					firsthtml = "<td style=\"background:#ffe8c5;\" title=\"#" + lineidx + ":该行与数据库数据有重复\"><div class=\"lang\">重复</div></td>"
				}
			}
		}
		html += "<tr>"
		html += firsthtml
		html += hrhtml
		html += "</tr>"
		cnt++
	}
	html += "</tbody>\n"
	html += "</table>\n"
	html += "</div>\n"
	html += "<input type=\"hidden\" name=\"total\" value=\"" + c.Tostr(cnt) + "\"/>\n"
	html += "<code>共" + c.Tostr(cnt) + "条数据</code>\n"
	return c.SuccJSON(w, r, map[string]any{
		"html":  html,
		"count": cnt,
	})
}
func Normal_importxls_data(w http.ResponseWriter, r *http.Request) bool {
	post := c.NewCiyPost(w, r)
	_, userid := admin.Verifyfast(r, c.CiyDB, post)
	if userid == 0 {
		return false
	}
	total := post.Getint("total")
	err := c.CiyDB.Tran(func() error {
		for i := 1; i <= total; i++ {
			istr := c.Tostr(i)
			id := post.Getint("id_" + istr)
			auditstatus := post.Get("auditstatus_" + istr)
			audituser := post.Get("audituser_" + istr)
			audittimes := post.Get("audittimes_" + istr)
			name := post.Get("name_" + istr)
			menuid := post.Get("menuid_" + istr)
			filesize := post.Get("filesize_" + istr)
			metre := post.Get("metre_" + istr)
			bankmoney := post.Get("bankmoney_" + istr)
			setdate := post.Get("setdate_" + istr)
			settimes := post.Get("settimes_" + istr)
			isuse := post.Get("isuse_" + istr)
			isopen := post.Get("isopen_" + istr)
			unit := post.Get("unit_" + istr)
			mauditstatus := post.Get("mauditstatus_" + istr)
			prodcata := post.Get("prodcata_" + istr)
			areacode := post.Get("areacode_" + istr)
			renzheng := post.Get("renzheng_" + istr)
			npcyc := post.Get("npcyc_" + istr)
			runsec := post.Get("runsec_" + istr)
			acttm := post.Get("acttm_" + istr)
			ton := post.Get("ton_" + istr)
			price := post.Get("price_" + istr)
			lat := post.Get("lat_" + istr)
			lng := post.Get("lng_" + istr)
			url := post.Get("url_" + istr)
			idcard := post.Get("idcard_" + istr)
			weightg := post.Get("weightg_" + istr)
			eartmpr := post.Get("eartmpr_" + istr)
			content := post.Get("content_" + istr)
			csql := c.NewCiySQL("demo_normal")
			csql.Where("name", name)
			csql.Column("id")
			chkid := c.Toint(c.CiyDB.Get1(csql))
			if chkid > 0 && ((id > 0 && chkid != id) || id == 0) {
				return fmt.Errorf("发现数据有重复")
			}
			updata := map[string]any{}
			updata["auditstatus"] = auditstatus
			updata["audituser"] = audituser
			updata["audittimes"] = audittimes
			updata["name"] = name
			updata["menuid"] = menuid
			updata["filesize"] = filesize
			updata["metre"] = metre
			updata["bankmoney"] = bankmoney
			updata["setdate"] = setdate
			updata["settimes"] = settimes
			updata["isuse"] = isuse
			updata["isopen"] = isopen
			updata["unit"] = unit
			updata["mauditstatus"] = mauditstatus
			updata["prodcata"] = prodcata
			updata["areacode"] = areacode
			updata["renzheng"] = renzheng
			updata["npcyc"] = npcyc
			updata["runsec"] = runsec
			updata["acttm"] = acttm
			updata["ton"] = ton
			updata["price"] = price
			updata["lat"] = lat
			updata["lng"] = lng
			updata["url"] = url
			updata["idcard"] = idcard
			updata["weightg"] = weightg
			updata["eartmpr"] = eartmpr
			updata["content"] = content
			updata["addtimes"] = c.Tostamp()
			csql = c.NewCiySQL("demo_normal")
			var err error
			if id == 0 {
				_, err = c.CiyDB.Insert(csql, updata)
			} else {
				csql.Where("id", id)
				_, err = c.CiyDB.Update(csql, updata)
			}
			if err != nil {
				return fmt.Errorf("导入失败:%v", err)
			}
		}
		return nil
	})
	if err != nil {
		return c.ErrJSON(w, err.Error())
	}
	return c.SuccJSON(w, r)
}
