<template>
    <div class="saga-recommend">
        <div v-if="hasData">
            <h4>当前资产：{{fm.FmName}}</h4>
            <div class="saga-change-name" v-if="!isChangeFor">
                <h3 class="saga-gray saga-explain">您可能需要快捷改值操作</h3>
                <!-- 智能推荐按钮 -->
                <div v-if="isChangeId">
                    <template v-if="changeList.length" v-for="item in changeList">
                <saga-button @click="getList(item)">修正 "{{getName(key)}}" 为 {{item.value}}</saga-button>
</template>
<template v-if="!changeList.length">
    <p>
        {{changeMsg}}</p>
</template>
        </div>
        <!-- 修正按钮 -->
        <div v-else>
          <saga-button @click="changeToNull">修正 "{{getName(key)}}" 为 {{noIdChangeVal}}</saga-button>
        </div>
      </div>
      <div class="saga-change-name" v-if="!isSameForCreate">
        <h3 class="saga-gray saga-explain">您可能需要快捷维护厂商库</h3>
<template>
    <saga-button v-if="!isChangeVender" @click="create">
        增加 {{obj.name}} “ {{val ? val : fm.Infos[key]}} ”</saga-button>
    <saga-button v-if="isChangeVender" @click="changeVender">更新厂商库中此{{obj.name}}对应值</saga-button>
</template>
        <!--<template v-else>
    <p>
        {{ !!message ? message : "请确定该信息点内有值"}}</p>
</template>-->
      </div>
      <div class="saga-change-name" v-if="elseBtnsShow">
        <h3 class="saga-gray saga-explain">您可能需要其他快捷操作</h3>
        <!-- <saga-button @click="checkVenders">先维护 xxx 信息点</saga-button> -->
        <saga-button @click="checkVenders" v-if="showBtn">批量维护 {{!!obj ? obj.name : ""}} 相关信息点</saga-button>
        <saga-button v-if="!showBtn">先维护 {{objMsg}}</saga-button>
        <!-- <saga-button @click="checkVenders"></saga-button> -->
      </div>
    </div>
    <div v-else class="saga-message">
      <p>{{!!dataMessage ? dataMessage : "请确定该信息点是支持推荐的信息点"}}</p>
    </div>
    <venders-change
      :create="isCreate"
      v-if="dialog.visible"
      ref="venders"
      :dialog="dialog"
      :infosKey="infosKey"
      :types="types"
      :fmData="fm"
      @change="loadFm"
      :title="isCreate ? '添加' + obj.name : '修改' + obj.name"
    ></venders-change>
  </div>
</template>
<script>
    import sagaButton from "./sagaButton"
    import vendersChange from "./vendersChange"
    import getVenderRecommend from "./findId"
    import tools from "@/assets/js/tools"
    import getJson from "@/utils/buildData/vendersUtils"
    import buildJson from "@/utils/buildData/buildJson"
    import cutHeader from "@/utils/cutHeader"
    import {
        upDateTableMain,
        getBasicMatch
    } from "@/api/request"
    export default {
        components: {
            sagaButton,
            vendersChange
        },
        data() {
            return {
                hasData: false,
                fm: {},
                infosKey: null,
                dialog: {
                    visible: false
                },
                createList: [],
                changeList: [],
                types: {},
                headers: [],
                message: "",
                obj: {},
                key: "",
                isCreate: false,
                showBtn: false,
                createShow: false,
                changeMsg: "", //修改的提示
                dataMessage: "⬅请点击资产信息点",
                falg: false, //上级页面传入的数值，用于实时请求
                val: null, //上级传入的val
                isSameForCreate: false,
                isChangeFor: false,
                isChangeVender: false,
                isChangeId: true, //是否为修改id
                noIdChangeVal: "",
                elseBtnsShow: true, //是否显示修改按钮
                msgTable: true,
                content: {}, //厂商库信息点
                objMsg: "相关信息点"
            }
        },
        created() {},
        mounted() {},
        methods: {
            //主页面重新加载
            loadFm() {
                this.$emit("loadData")
            },
            //根据id获得信息点名称
            getName(code) {
                if (!!code) {
                    let name = ""
                    this.headers.map(item => {
                        if (item.InfoPointCode == code) {
                            name = item.InfoPointName
                        }
                    })
                    return name
                } else {
                    return ""
                }
            },
            //修改
            checkVenders() {
                this.isCreate = false
                this.dialog.visible = true
                this.$nextTick(_ => {
                    this.$refs.venders.getData()
                })
            },
            //获取表头
            changeObj() {
                buildJson.map(item => {
                    if (item.name == "型号") {
                        item.options = []
                        item.infosArr = []
                        this.headers.map(child => {
                            if (child.FirstTag == "技术参数" ||
                                child.InfoPointCode == "Specification" ||
                                child.InfoPointCode == "MaintainPeriod" ||
                                child.InfoPointCode == "ServiceLife") {
                                item.infosArr.push(child.InfoPointCode)
                                let option = {
                                    key: "contact.infos." + child.InfoPointCode,
                                    label: child.InfoPointName,
                                    optLabel: child.InfoPointCode,
                                    type: child.DataType,
                                    dataSource: child.DataSource,
                                    FirstTag: child.FirstTag,
                                    SecondTag: child.SecondTag
                                }
                                if (child.InfoPointCode == "Specification") {
                                    option.key = "content.specificationName"
                                }
                                item.options.push(option)
                            }
                        })
                        item.options = cutHeader(item.options)
                    }
                })
            },
            changeToNull() {
                //   let param = {
                //     FmId: this.fm.FmId,
                //     Infos: {
                //       [this.key]: null
                //     }
                //   }
                //   this.updateMain(param)
                console.log(this.noIdChangeVal, "this.noIdChangeVal")
                this.fm.Infos[this.key] = this.noIdChangeVal
            },
            //上级页面传输的数据
            randerData(idData, infosKey, headers, falg = false, val = null) {
                this.isChangeVender = false
                console.log(idData, infosKey, headers, falg, "falg")
                this.falg = falg
                this.val = val
                this.fm = tools.deepCopyObj(idData)
                this.headers = headers
                this.changeObj()
                this.infosKey = infosKey
                this.message = ""
                this.key = infosKey.split(".")[1]
                this.obj = getJson(this.infosKey.split(".")[1])
                console.log("数据请求", this.obj)
                if (!!this.obj) {
                    console.log("有data")
                    this.hasData = true
                    this.getDataForm()
                } else {
                    this.hasData = false
                }
            },
            changeVender() {
                // 修改厂商库中对应的值
                console.log("修改厂商库中的值", this.obj, this.key)
                let webArr = ["SupplierWeb", "InsurerWeb", "MaintainerWeb"],
                    //三大厂商的key
                    keysArr = ["DPInsurerID", "DPSupplierID", "DPMaintainerID"]
                //如果是三大厂商的网址
                if (webArr.indexOf(this.key) > -1) {
                    let param = {
                        venderId: this.fm.Infos[this.obj.infosKey],
                        website: this.fm.Infos[this.key]
                    }
                    this.obj.updateVender(param, res => {
                        this.updateKey(this.key, this.fm)
                    })
                    return false
                } else if (keysArr.indexOf(this.obj.infosKey) > -1) {
                    let param = {
                        venderId: this.fm.Infos[this.obj.infosKey],
                        projectId: this.$route.query.projId
                    }
                    //如果存在content的联系人
                    console.log(this.content, "content")
                    if (this.content.hasOwnProperty("contact")) {
                        let contents = this.content.contact
                        for (let k in contents) {
                            param[k] = contents[k]
                        }
                    }
                    param[[this.getKey(this.obj.options, this.key)]] = this.fm.Infos[this.key]
                    this.obj.update(param, res => {
                        this.updateKey(this.key, this.fm)
                    })
                    return false
                } else {
                    let param = {
                        specificationId: this.fm.Infos.DPSpecificationID,
                        infos: {
                            [this.key]: this.fm.Infos[this.key]
                        }
                    }
                    this.obj.updateVender(param, res => {
                        this.updateKey(this.key, this.fm)
                    })
                    return false
                }
            },
            updateKey(key, obj) {
                let param = {
                    FmId: obj.FmId,
                    Infos: {
                        [key]: null
                    }
                }
                this.updateMain(param)
            },
            /**
             * @param arr 传入的数组
             * @param key 传入的key
             * 
             * @return key 对应的key
             */
            getKey(arr, key) {
                let returnKey = ""
                arr.map(item => {
                    if (item.optLabel == key) {
                        returnKey = item.key.split(".")[1]
                        console.log(returnKey, item, "item")
                    }
                })
                return returnKey
            },
            //有obj的信息时
            getDataForm() {
                let idArr = ["DPManufacturerID", "DPSupplierID", "DPInsurerID", "DPMaintainerID", "DPSpecificationID", "DPBrandID", "DPSpecificationID"]
                //点击以下按钮触发按钮事件
                let vendersArr = ["Manufacturer", "Supplier", "Maintainer", "Insurer", "Brand", "Specification"]
                if (!!this.fm.Infos[this.obj.infosKey]) {
                    this.falgChange(true)
                } else {
                    this.falgChange(false)
                }
            },
            //falg为是否存在id
            falgChange(falg) {
                let vendersArr = ["Manufacturer", "Supplier", "Maintainer", "Insurer", "Brand", "Specification"]
                if (this.val || !!this.fm.Infos[this.key]) {
                    //存在id且单元格存在值
                    if (falg) {
                        if (this.falg && vendersArr.indexOf(this.key) > -1) {
                            this.noIdDo()
                        } else {
                            this.getVendersList()
                        }
                    } else {
                        // 没有id
                        this.noIdDo()
                    }
                } else {
                    //不存在值
                    // this.isChangeFor = false
                    // this.isSameForCreate = true
                    // this.changeList = []
                    this.noIdDo()
                    // this.changeMsg = "请确定该单元格内存在值"
                }
            },
            //没有id执行
            noIdDo() {
                console.log("没有id")
                let param = {
                        infoCode: this.key,
                        infoValue: this.val || this.fm.Infos[this.key]
                    },
                    falg = true
                this.createShow = true
                this.showBtn = false
                this.elseBtnsShow = true
                if (this.key == "Brand") {
                    param.manufacturerID = this.fm.Infos.DPManufacturerID
                }
                if (this.key == "Specification") {
                    param.manufacturerID = this.fm.Infos.DPManufacturerID
                    param.brandID = this.fm.Infos.DPBrandID
                    param.eqFamily = this.fm.Family
                }
                for (let k in param) {
                    if (!param[k]) {
                        falg = false
                    }
                }
                console.log(falg, "falg")
                //如果传参中某个值为空不发生请求
                if (!falg) {
                    this.noShowTop12()
                    return false
                } else {
                    this.elseBtnsShow = false
                }
                console.log(this.obj.infosArr[0], this.infosKey, "this.infosKey")
                if (this.obj.infosArr[0] != this.key) {
                    console.log("其他信息点")
                    this.noShowTop12()
                    return false
                }
                getVenderRecommend(param, res => {
                    this.changeList = res.content || []
                    this.isChangeId = true
                    this.isSameForCreate = false
                    this.isChangeFor = false
                    console.log(this.changeList, "changeList")
                    if (!!this.changeList && this.changeList.length == 1) {
                        if (this.changeList[0].value == this.fm.Infos[this.key] &&
                            this.changeList[0].id == this.fm.Infos["DP" + this.key + "ID"]) {
                            this.isSameForCreate = true
                            this.isChangeFor = true
                            if (!!this.val && this.val != this.fm.Infos[this.key]) {
                                this.isChangeFor = false
                                this.isSameForCreate = false
                            }
                        }
                    }
                    if (res.content[0] && res.content[0].similarity == 100) {
                        this.changeList = []
                        this.isSameForCreate = true
                        this.isChangeFor = false
                    }
                    if (this.changeList.length <= 0) {
                        //   this.changeMsg = "不存在符合条件的推荐"
                    }
                })
            },
            //第一栏第二栏不显示
            noShowTop12() {
                if (!this.val && !this.fm.Infos[this.key]) {
                    this.elseBtnsShow = false
                }
                console.log(this.obj.infosKey, this.fm.Infos)
                //型号
                if (this.obj.infosKey == "DPSpecificationID") {
                    if (!this.fm.Infos.DPManufacturerID) {
                        this.elseBtnsShow = true
                        this.objMsg = "生产厂家"
                    } else if (!this.fm.Infos.DPBrandID) {
                        this.elseBtnsShow = true
                        this.objMsg = "品牌"
                    } else if (!this.fm.Infos.DPSpecificationID) {
                        console.log("设备型号")
                        this.elseBtnsShow = true
                        this.objMsg = "设备型号"
                    }
                }
                //品牌
                if (this.obj.infosKey == "DPBrandID") {
                    if (!this.fm.Infos.DPManufacturerID) {
                        this.objMsg = "生产厂家"
                    }
                }
                //生产厂家
                if (this.obj.infosKey == "DPManufacturerID") {
                    this.elseBtnsShow = false
                }
                //供应商
                if (this.obj.infosKey == "DPSupplierID") {
                    if (!this.fm.Infos.DPSupplierID) {
                        console.log("没有供应商id")
                        this.elseBtnsShow = false
                        if (this.key != "Supplier") {
                            this.elseBtnsShow = true
                        }
                        this.objMsg = "供应商单位名称"
                    }
                }
                //维修商
                if (this.obj.infosKey == "DPMaintainerID") {
                    if (!this.fm.Infos.DPMaintainerID) {
                        console.log("没有维修商id")
                        this.elseBtnsShow = false
                        if (this.key != "Maintainer") {
                            this.elseBtnsShow = true
                        }
                        this.objMsg = "维修商单位名称"
                    }
                }
                //保险公司
                if (this.obj.infosKey == "DPInsurerID") {
                    if (!this.fm.Infos.DPInsurerID) {
                        console.log("没有保险id")
                        this.elseBtnsShow = false
                        if (this.key != "Insurer") {
                            this.elseBtnsShow = true
                        }
                        this.objMsg = "保险公司名称"
                    }
                }
                this.isSameForCreate = true
                this.isChangeFor = true
            },
            //当前单元格内存在id且单元格存在值
            getVendersList() {
                //四大厂商名称
                this.isChangeId = true
                let venderIdArr = ["DPManufacturerID", "DPSupplierID", "DPInsurerID", "DPMaintainerID", "DPBrandID"],
                    vendersArr = ["Manufacturer", "Supplier", "Maintainer", "Insurer", "Brand"],
                    infosKey = this.obj.infosKey
                this.showBtn = true
                this.elseBtnsShow = true
                //获取label
                let ownLabel = ""
                this.obj.options.map(item => {
                    if (item.optLabel == this.key) {
                        ownLabel = item.key
                    }
                })
                if (venderIdArr.indexOf(infosKey) > -1) {
                    let param = {
                        venderId: this.fm.Infos[infosKey],
                        projectId: this.$route.query.projId
                    }
                    if (infosKey == "DPBrandID") {
                        param = {
                            brandId: this.fm.Infos[infosKey]
                        }
                    }
                    this.obj.getList(param, res => {
                        console.log(this.key, this.obj.options, res, ownLabel, "ownLabel")
                        let optArr = ownLabel.split("."),
                            optContent = ""
                        if (this.obj.infosKey == "DPBrandID") {
                            optContent = res[optArr[0]][optArr[1]]
                        } else {
                            optContent = res.content[optArr[0]][optArr[1]]
                        }
                        if (optContent == (this.val || this.fm.Infos[this.key])) {
                            //厂商库中的值与现有的值相等
                            this.isChangeFor = true
                            this.isSameForCreate = true
                            let keysBtns = ["DPBrandID", "DPManufacturerID"]
                            if (keysBtns.indexOf(this.obj.infosKey) > -1) {
                                this.elseBtnsShow = false
                            }
                        } else {
                            if (!optContent) {
                                //如果厂商库中没有值
                                console.log("没有该信息点")
                                this.isChangeFor = true
                                this.isChangeVender = true
                                this.isSameForCreate = false
                            } else {
                                //有值
                                console.log("有值,且值不同")
                                this.isChangeId = false
                                this.hasData = true
                                this.content = res.content
                                //修改的值（其实做置空操作）
                                this.noIdChangeVal = optContent
                                this.isChangeFor = false
                                this.isSameForCreate = false
                                this.isChangeVender = true
                            }
                        }
                    })
                }
                if (infosKey == "DPSpecificationID") {
                    let paramData = {
                        specificationId: this.fm.Infos[infosKey]
                    }
                    this.obj.getList(paramData, res => {
                        let optContent = res.content.infos[this.key]
                        console.log(optContent, this.val, this.fm.Infos[this.key], "optContent")
                        if (optContent == (this.val || this.fm.Infos[this.key])) {
                            console.log("有值，且值相同")
                            this.isChangeFor = true
                            this.isSameForCreate = true
                            if (this.key == "Specification") {
                                this.elseBtnsShow = false
                            } else {
                                this.elseBtnsShow = true
                            }
                        } else {
                            if (!optContent) {
                                //如果厂商库中没有值
                                console.log("没有该信息点")
                                this.isChangeFor = true
                                this.isChangeVender = true
                                this.isSameForCreate = false
                            } else {
                                //有值
                                console.log("有值,且值不同")
                                this.isChangeId = false
                                this.hasData = true
                                //修改的值（其实做置空操作）
                                this.noIdChangeVal = optContent
                                this.isChangeFor = false
                                this.isSameForCreate = false
                                this.isChangeVender = true
                            }
                        }
                    })
                }
                if (vendersArr.indexOf(this.key) > -1) {
                    this.showBtn = true
                }
            },
            //创建函数
            create(item) {
                // console.log(this.obj.infosKey)
                // let param;
                // if(this.obj.infosKey == "DPBrandID" || this.obj.infosKey == "DPManufacturerID"){
                //     if(this.obj.infosKey == "DPBrandID"){
                //         param = {
                //             "venderId": this.fm.Infos.DPManufacturerID,     //String,必填,生产商id
                //             "name": this.fm.Infos.Brand,              //String,必填,品牌名称   
                //         }
                //     }else{
                //         param = {
                //             "name": this.fm.Infos.Manufacturer,          
                //         }
                //     }
                //     this.obj.createFunc(param,res=>{
                //     })
                // }
                this.isCreate = true
                this.dialog.visible = true
                this.$nextTick(_ => {
                    this.$refs.venders.getCreateData()
                })
            },
            updateMain(param) {
                upDateTableMain({
                    ProjId: this.$route.query.projId,
                    UserId: this.$route.query.userId
                }, [param]).then(res => {
                    if (res.data.Result == "success") {
                        this.loadFm()
                    } else {
                        this.$message.error("保存出错")
                    }
                })
            },
            //点击按钮，对表格操作
            getList(data) {
                //   this.fm.Infos[this.key] = data.value
                let infos = tools.deepCopyObj(this.fm.Infos)
                infos[this.key] = data.value
                let param = {
                    "projectId": this.$route.query.projId,
                    "criterias": [{
                        id: this.fm.FmId,
                        family: this.fm.Family,
                        infos: infos
                    }]
                }
                console.log(param, "paramparam")
                this.getIdForVender(param)
            },
            //判断文案是否相同
            getIdForVender(param) {
                getBasicMatch(param).then(res => {
                    if (res.data.result == "success") {
                        let myParam = res.data.content.map(item => {
                            return {
                                Family: item.family,
                                FmId: item.id,
                                Infos: item.infos
                            }
                        })
                        this.updateMain(myParam[0])
                    } else {
                        this.$message.error("请求错误" + res.data.resultMsg)
                    }
                }).catch(error => {
                    this.$message.error(error)
                })
            },
        }
    }
</script>
<style lang="less" scoped>
    .saga-recommend {
        height: 100%;
        overflow-y: auto; //   background-color: red;
        .saga-gray {
            color: #b7c3c8;
        }
        .saga-change-name {
            padding: 8px;
            min-height: 100px; // background-color: yellow;
            border-bottom: 1px solid #ccc;
            .saga-explain {
                font-size: 17px;
                font-weight: 600;
            }
        }
    }
    .saga-message {
        height: 100vh;
        line-height: 100vh;
        font-size: 20px;
        color: #b7c3c8;
    }
</style>
