<template>
  <el-dialog :title="title" :visible.sync="dialog.visible" center>
    <div class="dialog-height">
      <h3>{{name}}</h3>
      <p>您可以在此一次性维护厂商库中上述厂商的资料</p>
      <div class="saga-view">
        <div class="saga-mine">
          <div class="saga-in" v-if="!create">
            <div class="saga-label"></div>
            <div class="saga-input">厂商库中已有的值</div>
            <div class="saga-button">当前资产的值</div>
          </div>
          <div v-if="obj.infosKey == 'DPSpecificationID' && create">
            <div style="line-height:32px;">
              <el-switch
                v-model="isCreateProduct"
                @change="changeSwitch"
                active-text="创建产品"
                inactive-text="选择产品"
              ></el-switch>
            </div>
            <div style="margin: 5px;">
              {{isCreateProduct ? "创建产品" : "选择产品"}}
              <el-input
                style="width:250px;"
                size="small"
                v-if="isCreateProduct"
                placeholder="请输入产品名"
                v-model="productName"
                clearable
              ></el-input>
              <el-select
                size="small"
                v-if="!isCreateProduct"
                v-model="productId"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.productId"
                  :label="item.name"
                  :value="item.productId"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="saga-ipnput-view">
            <template v-for="(item,index) in labelList" v-if="obj.infosKey != 'DPSpecificationID' ">
              <data-fill
                v-if="isShow(item,index)"
                :isCreated="create"
                :renderData="item"
                @change="changefillData"
              ></data-fill>
            </template>
            <template v-if="obj.infosKey == 'DPSpecificationID'">
              <div v-for="item in labelList">
                <!-- 一级标签 -->
                <h3 style="line-height:32px; color: green;">{{item.FirstTag}}</h3>
                <div v-if="child.SecondTag != '设备厂家' || create" v-for="child in item.details">
                  <!-- 二级标签 -->
                  <h4 style="line-height:32px;padding-left:20px;color: #409EFF;">{{child.SecondTag}}</h4>
                  <div v-for="detail in child.details">
                    <data-fill
                      v-if="detail.key"
                      :isCreated="create"
                      :renderData="detail"
                      @change="changefillData"
                    ></data-fill>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="isCreate">{{ create ? "创建" : " 保存并更新厂商库"}}</el-button>
      <el-button @click="dialog.visible = false">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import dataFill from "./dataFill"
import getJson from "@/utils/buildData/vendersUtils"
import {
  upDateTableMain,
  getProductList
} from "@/api/request"
import cutHeader from "@/utils/cutHeader"
import tools from "@/assets/js/tools"
export default {
  components: {
    dataFill
  },
  props: {
    dialog: {
      type: Object,
      default: function () {
        return {
          visible: false
        }
      }
    },
    types: {
      type: Object
    },
    fmData: {
      type: Object
    },
    infosKey: {
      type: String
    },
    create: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      name: "",
      labelList: [],
      obj: {},
      isCreateProduct: true,
      productName: "",
      productId: "",
      productOptions: [],
      fm: {
        Infos: {}
      }
    }
  },
  created() { },
  mounted() { },
  methods: {
    isShow(item, index) {
      let falg = false
      console.log(item, index)
      if (!item.key || index == 0) {
        falg = false
      } else {
        falg = true
      }
      if (this.create) {
        falg = true
      }
      return falg
    },
    //修改开关
    changeSwitch() {
      if (!this.isCreateProduct) {
        let param = {
          brandId: this.fm.Infos.DPBrandID,
          familyCode: this.fm.Family
        }
        getProductList(param, res => {
          this.productOptions = res.content
        })
      }
    },
    //获取创建信息
    getCreateData() {
      this.fm = tools.deepCopyObj(this.fmData)
      console.log(this.gm, this.fmData, "fmData")
      this.obj = getJson(this.infosKey.split(".")[1])
      if (this.obj.infosKey != "DPSpecificationID") {
        this.labelList = this.obj.options.map(item => {
          let keyArr = item.key.split("."), data = ""
          item.value = this.fm.Infos[item.optLabel] || ""
          return item
        })
      } else {
        this.labelList = this.obj.options.map(item => {
          if (item.details && item.details.length) {
            //一级标签
            item.details.map(child => {
              if (child.details && child.details.length) {
                child.details.map(details => {
                  details.value = this.fm.Infos[details.optLabel] || ""
                  return details
                })
              }
              return child
            })
          }
          return item
        })
      }
    },
    //创建请求
    createOwn() {
      let venderIdArr = ["DPManufacturerID", "DPSupplierID", "DPInsurerID", "DPMaintainerID", "DPBrandID"]
      console.log(this.fm)
      if (venderIdArr.indexOf(this.obj.infosKey) > -1) {
        let param = {}
        param.name = this.getMess('vender.name')
        if (this.obj.infosKey != "DPManufacturerID") {
          param.website = this.getMess('vender.website')
        }
        //当其id为品牌id
        if (this.obj.infosKey == "DPBrandID") {
          param.name = this.getMess('content.name')
          param.venderId = this.fm.Infos.DPManufacturerID
        }
        //新建
        this.obj.createFunc(param, res => {
          this.fm.Infos[this.obj.infosKey] = res.id
          param = {}
          param.venderId = this.fm.Infos[this.obj.infosKey]
          param.projectId = this.$route.query.projId
          //如果存在联系人请求
          if (!!this.obj.update) {
            if (this.obj.name == "生产商") {
              param.name = this.getMess('vender.name')
            } else {
              param.phone = this.getMess('contact.phone')
              param.name = this.getMess('contact.name')
              param.fax = this.getMess('contact.fax')
              param.email = this.getMess('contact.email')
            }
            //发起请求
            this.obj.update(param, res => {
              for (let k in this.labelList) {
                this.changeFmData(this.labelList[k].optLabel, this.fm.Infos)
              }
              this.updateFm(this.fm)
            })
          } else {
            for (let k in this.labelList) {
              this.changeFmData(this.labelList[k].optLabel, this.fm.Infos)
            }
            if (this.obj.infosKey == "DPBrandID") {
              this.fm.Infos.Brand = this.getMess('content.name')
              this.fm.Infos.DPSpecificationID = null
            }
            //如果修改的是生产厂家，品牌型号清空
            if (this.obj.infosKey == "DPManufacturerID") {
              this.fm.Infos.DPBrandID = null
              this.fm.Infos.DPSpecificationID = null
            }
            this.updateFm(this.fm)
          }
        })
      }
      let brandId = this.fm.Infos.DPBrandID
      if (this.obj.infosKey == "DPSpecificationID") {
        let param = tools.deepCopyObj(this.fm)
        param.Infos = {}
        //取infos中的数据
        this.labelList.map(item => {
          if (item.details && item.details.length) {
            //一级标签
            item.details.map(child => {
              if (child.details && child.details.length) {
                child.details.map(details => {
                  if (!!details.value) {
                    param.Infos[details.optLabel] = details.value || null
                  }
                })
              }
            })
          }
          return item
        })
        console.log(param, "param")
        //创建产品且产品名为空
        if (this.isCreateProduct && !this.productName) {
          this.$message.error("请确定创建产品名不为空")
          return
        }
        //选择产品，产品的id为空
        if (!this.isCreateProduct && !this.productId) {
          this.$message.error("请确定该型号所归属的产品")
          return
        }
        //如果保养周期和使用寿命中有一个为空
        // if (!param.Infos.MaintainPeriod || !param.Infos.ServiceLife || !param.Infos.Specification) {
        //   this.$message.error("设备型号、保养周期和使用寿命为必填项")
        //   return
        // }
        //是否是创建
        if (this.isCreateProduct) {
          let produceParam = {
            brandId: brandId,
            name: this.productName,
            eqFamily: this.fm.Family
          }
          this.obj.createProduct(produceParam, res => {
            let speParam = {
              productId: res.id,
              name: param.Infos.Specification,
              infos: param.Infos
            }
            this.createSpecification(speParam)
          })
        } else {
          let speParam = {
            productId: this.productId,
            name: param.Infos.Specification,
            infos: param.Infos
          }
          this.createSpecification(speParam)
        }
      }
    },
    createSpecification(param) {
      this.obj.createFunc(param, res => {
        let updateParam = tools.deepCopyObj(this.fm)
        updateParam.Infos = {}
        updateParam.Infos.DPSpecificationID = res.id
        this.labelList.map(item => {
          if (item.details && item.details.length) {
            //一级标签
            item.details.map(child => {
              if (child.details && child.details.length) {
                child.details.map(details => {
                  if (!!details.value) {
                    updateParam.Infos[details.optLabel] = null
                  }
                })
              }
            })
          }
        })
        console.log(updateParam, "updateParam")
        this.updateFm(updateParam)
      })
    },
    //判断是否创建
    isCreate() {
      if (this.create) {
        this.createOwn()
      } else {
        this.update()
      }
    },
    //修改默认填入信息
    changefillData(data) {
      this.labelList.map(item => {
        if (item.key == data.key) {
          item.value = item.oldValue
        }
      })
    },
    getData() {
      this.fm = tools.copyArr(this.fmData)
      console.log(this.fmData, this.fm)
      this.isCreateShow = false
      this.obj = {}
      this.obj = getJson(this.infosKey.split(".")[1])
      let venders = ["DPSupplierID", "DPInsurerID", "DPManufacturerID"]
      if (!!this.obj) {
        let param = {
          venderId: this.fm.Infos[this.obj.infosKey],
          projectId: this.$route.query.projId
        }
        if (this.obj.infosKey == "DPBrandID") {
          param = {
            brandId: this.fm.Infos[this.obj.infosKey]
          }
        }
        if (this.obj.infosKey == "DPSpecificationID") {
          param = {
            specificationId: this.fm.Infos[this.obj.infosKey]
          }
        }
        this.obj.getList(param, res => {
          console.log(res, venders.indexOf(this.obj.infosKey))
          if (venders.indexOf(this.obj.infosKey) > -1) {
            this.name = res.content.vender.name
          } else if (this.obj.infosKey == "DPBrandID") {
            this.name = res.content.name
          } else {
            let content = res.content
            this.name = content.venderName + '-' + content.brandName + '-' + content.productName + '-' + content.specificationName
          }
          this.labelList = []
          if (this.obj.infosKey == "DPSpecificationID") {
            this.labelList = this.obj.options.map(item => {
              if (item.details && item.details.length) {
                //一级标签
                item.details.map(child => {
                  if (child.details && child.details.length) {
                    child.details.map(details => {
                      let detailsKey = details.key.split("."),
                        data = ""
                      let resp = res.content
                      for (let i = 0; i < detailsKey.length; i++) {
                        if (!!resp[detailsKey[i]]) {
                          data = resp[detailsKey[i]]
                          resp = resp[detailsKey[i]]
                        } else {
                          data = ""
                        }
                      }
                      details.value = data
                      details.oldValue = this.fm.Infos[details.optLabel]
                      return details
                    })
                  }
                  return child
                })
              }
              return item
            })
          } else {
            this.labelList = this.obj.options.map(item => {
              let keyArr = item.key.split(".")
              let data = ""
              let resp = res.content
              for (let i = 0; i < keyArr.length; i++) {
                if (!!resp[keyArr[i]]) {
                  data = resp[keyArr[i]] || ""
                  resp = resp[keyArr[i]]
                } else {
                  data = ""
                }
              }
              item.value = data || ""
              item.oldValue = this.fm.Infos[item.optLabel] || ""
              return item
            })
          }
        })
      } else {
        this.$message.error("该信息点不支持推荐")
      }
    },
    //修改六大参数
    update() {
      if (!!this.obj) {
        if (this.obj.name == "型号") {
          this.updateSpecification()
        } else {
          this.updateVer()
        }
      }
    },
    updateSpecification() {
      console.log("修改型号", this.obj)
      let param = {
        specificationId: this.fm.Infos.DPSpecificationID,
        name: "",
        infos: {}
      }
      console.log(this.labelList)
      //   this.labelList.map(item => {
      //     param.infos[item.optLabel] = item.value || null
      //     if (item.optLabel == "Specification") {
      //       param.name = item.value || null
      //     }
      //   })
      this.labelList.map(item => {
        if (item.details && item.details.length) {
          item.details.map(child => {
            if (child.details && child.details.length) {
              child.details.map(details => {
                param.infos[details.optLabel] = details.value || null
                if (details.optLabel == "Specification") {
                  param.name = details.value || null
                }
              })
            }
          })
        }
      })
      console.log(param)
      this.obj.updateVender(param, res => {
        this.dialog.visible = false
        this.$emit("change")
      })
    },
    //修改供应商
    updateVer() {
      if (!!this.obj.updateVender) {
        this.updateVender()
      } else {
        this.updatePhone()
      }
    },
    //修改
    updateVender() {
      let param = {}
      param.venderId = this.fm.Infos[this.obj.infosKey]
      param.projectId = this.$route.query.projId
      param.name = this.getMess('vender.name')
      param.website = this.getMess('vender.website')
      if (this.obj.infosKey == "DPBrandID") {
        param = {
          brandId: this.fm.Infos[this.obj.infosKey],
          name: this.getMess('content.name')
        }
      }
      console.log(param, "param")
      this.obj.updateVender(param, res => {
        this.updatePhone()
      })
    },
    //修改厂商联系人信息
    updatePhone() {
      let param = {}
      param.venderId = this.fm.Infos[this.obj.infosKey]
      param.projectId = this.$route.query.projId
      if (this.obj.name == "生产商") {
        param.name = this.getMess('vender.name')
      } else {
        param.phone = this.getMess('contact.phone')
        param.name = this.getMess('contact.name')
        param.fax = this.getMess('contact.fax')
        param.email = this.getMess('contact.email')
      }
      this.obj.update(param, res => {
        for (let k in this.labelList) {
          this.changeFmData(this.labelList[k].optLabel, this.fm.Infos)
        }
        // this.dialog.visible = false
        this.updateFm(this.fm)
      })
    },
    //修改资产
    updateFm(param) {
      let list = tools.copyArr(param)
      upDateTableMain({
        ProjId: this.$route.query.projId,
        UserId: this.$route.query.userId
      }, [list]).then(res => {
        if (res.data.Result == "success") {
          this.$emit("change")
          console.log("venderChange")
          this.dialog.visible = false
        } else {
          this.$message.error("请求错误:" + res.data.ResultMsg)
        }
      }).catch(_ => {
        this.$message.error("请求发生错误")
      })
    },
    changeFmData(key, infos) {
      this.labelList.map(item => {
        if (item.optLabel == key) {
          if (item.value == infos[item.optLabel]) {
            infos[item.optLabel] = null
          }
        }
      })
    },
    getMess(key) {
      let data = ""
      this.labelList.map(item => {
        if (item.key == key) {
          data = item.value
        }
      })
      return data
    }
  },
  watch: {
    dialog: {
      deep: true,
      handler: function (old, val) {
        if (this.dialog.visible) {
          this.getData()
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.dialog-height {
  max-height: 600px;
  .saga-ipnput-view {
    max-height: 500px;
    overflow-y: auto;
  }
  .saga-in {
    display: flex;
    margin: 10px 0;
    .saga-label {
      flex-grow: 5;
      width: 80px;
    }
    .saga-input {
      flex-grow: 6;
    }
    .saga-button {
      flex-grow: 5;
      width: 120px;
    }
  }
}
</style>
