<template>
  <div>
    <div v-if="contractChangeReason == ''">
      <TitleWithCircle title="模版" style="margin-bottom: 20px;" />
      <el-form :model="mbinfo" :rules="rulesmbinfo" ref="rulesmbinfoForm" label-width="130px" class="demo-ruleForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板" prop="type">
              <el-select filterable v-model="mbinfo.type" placeholder="请选择" style="width: 100%;" @change="changeRelatedMerchants">
                <el-option :label="item.templateName" :value="index" v-for="(item,index) in mbData" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <TitleWithCircle title="合同信息" style="margin-bottom: 20px;" />
      <mbadd v-if="isshow" ref="rulesallForm" :list1="list1" :isdel="isdel" />
      <div style="margin-top: 20px;margin-left: 65px;">
        <el-button @click="close()" class="buttonHover" style="color: #606266;border: 1px solid #DBDBDB;background-color: #fff;">取消</el-button>
        <el-button @click="add()" style="background-color: #3F9B6A;color: #fff;">确定</el-button>
        <el-button @click="ylht()" style="background-color: #3F9B6A;color: #fff;">预览</el-button>
      </div>
    </div>
    <div v-else>
      <TitleWithCircle title="合同信息" style="margin-bottom: 20px;" />
      <mbadd v-if="isshow" ref="rulesallForm" :list1="list1" />
      <div style="margin-top: 20px;margin-left: 65px;">
        <el-button @click="close()" class="buttonHover" style="color: #606266;border: 1px solid #DBDBDB;background-color: #fff;">取消</el-button>
        <el-button @click="add1()" style="background-color: #3F9B6A;color: #fff;">确定</el-button>
        <el-button @click="ylht()" style="background-color: #3F9B6A;color: #fff;">预览</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import TitleWithCircle from '@/components/top/index';
  import mbadd from '@/components/change/mbadd';
  import {contractinsertAdd} from '@/api/manage.js'
  import {
    cereContractTemplate,cerePlatformMerchant
  } from '@/api/newly.js'
  import {
    dataInprotDocument,modifyResourceStatus,
    cereAssetShopInformationqueryByPage,cereAssetShopInformationedit
  } from '@/api/newly.js'
import {
    msgedit
  } from '@/api/cereBusinessInfo'
  import {
    AdvertiserInfoEdit
  } from '@/api/advertisement.js'
  import {
    cereContractInformation
  } from '@/api/commodityLease.js'
  export default {
    components: {
      TitleWithCircle,
      mbadd
    },
    data() {
      return {
        mbinfo:{
          type:''
        },
        onmbinfo:{},
        mbData:[],
        list1: [],
        rulesmbinfo:{
          type: [{
            required: true,
            message: '请选择模板',
            trigger: 'change'
          }],
        },
        isshow: false,
        formInline: {
          // 合同类型
          contractType: '',
          // 合同编号
          contractNumber: '',
          // 标段号
          sectionNumber: '',
          // 合同名称
          contractName: '',
          // 押金
          earnestMoney: '',
          // 合同签订日期
          contractSigningDate: '',
          // 合同终止日期
          contractTerminationDate: '',
          // 起租日期
          leaseStartDate: '',
          // 付款周期
          paymentCycle: '',
          // 合同金额（租金）
          contractAmount: '',
          // 付款日
          paymentDay: '',
          // 承租人名称
          tenantName: '',
          // 承租人联系电话
          tenantTelephone: '',
          // 承租人银行账号
          tenantBankAccount: '',
          // 关联商家
          relatedMerchants: '',
          // 商铺编号(绑定资源)
          shopNumber: '',
          // 合同附件
          appendicesContract: '',
          //合同状态
          dataStatus: '4',
          //模版信息
          templateInformation:'',
          //模版url
          templateInformationUrl:''
        },
        templateAttachment:'',
        AddData:[],
        dpinfo:null
      }
    },
    props: {
      info: {
        type: Object,
        default: {}
      },
      isdel: {
        type: String,
        default:''
      },
      contractChangeReason: {
        type: String,
        default: ''
      },
    },
    async created() {
      this.getmb()
      console.error({...this.info})
      // console.error(this.templateInformation)
      if(this.info.id) {
        if(this.info.cereBasicInformationShop && this.info.cereBasicInformationShop.id) {
          this.AddData.push(this.info.cereBasicInformationShop)
        }
        if(this.info.cereAdvertisingInformation && this.info.cereAdvertisingInformation.id) {
          this.AddData.push(this.info.cereAdvertisingInformation)
        }
        if(this.info.cereBasicInformationVenue && this.info.cereBasicInformationVenue.id) {
          this.AddData.push(this.info.cereBasicInformationVenue)
        }
        cereAssetShopInformationqueryByPage({"pageNumber":0,"pageSize":10,"contractId":this.info.id}).then(res => {
          console.error(res.data.content)
          if(res.data.content.length>0){
            this.dpinfo = res.data.content[0]
          }
        })
        // for (let index = 0; index < this.shopList.length; index++) {
        //   const element = this.shopList[index];
        //   console.error(element)
        //   if(element.phone == this.info.applicant) {
        //     this.shopId = element.id+''
        //     this.formInline.relatedMerchants = element.id+''
        //     this.formInline.tenantName = element.name
        //     this.formInline.tenantTelephone = element.phone
        //   }
        // }
      }
      if(this.info.templateInformation) {
        let listall = JSON.parse(this.info.templateInformation)
        console.error(listall)
        let listallcl = listall.map((item) => {
          if(item.type != '资源' && item.type != '商家' && item.key != 'tenantName' && item.key != 'tenantTelephone') {
            item.value = ''
            return item;
          } else {
            item.ishow = true
            return item
          }
        });
        // console.error(listallcl)
        this.list1 = listallcl
        this.isshow = true
      }
      if(this.info.templateInformationUrl){
        this.templateAttachment =  this.info.templateInformationUrl
      }
    },
    methods: {
      async add1() {
        // this.addinfo1()
        // return
        let isjx = await this.$refs.rulesallForm.yanzhen()
        console.error(isjx)
        if(isjx) {
          console.error(']]]]]')
          this.addinfo1()
        }
      },
      async addinfo1() {
        let dataStatus = this.contractChangeReason == '合同变更' ? '2' : this.contractChangeReason == '合同续约' ? '2' : this.contractChangeReason == '合同终止' ? '3' : '1'
        let info1 = {}
        for (let index = 0; index < this.list1.length; index++) {
          const element = this.list1[index];
          console.error({...element})
          if(element.type == '资源') {
            if(element.value && typeof element.value == 'object') {
              if (element.value.shopName) {
                info1.shopNumber = 'sp' + element.value.id
              } else if (element.value.advertisingType) {
                info1.shopNumber = 'gg' + element.value.id
              } else {
                info1.shopNumber = 'cd' + element.value.id
              }
            }
          }else if(element.type == '商家') {
            info1.relatedMerchants = element.value
          } else{
            info1[element.key] = element.value+''
          }
          
        }
        console.error(info1)
        for (let key in info1) {
          if (this.formInline.hasOwnProperty(key)) {
            this.formInline[key] = info1[key];
          }
        }
        this.formInline.templateInformation = JSON.stringify(this.list1)
        let from = {
          ...this.formInline,
          contractChangeReason: this.contractChangeReason,
          dataStatus: dataStatus,
          contractNumber: this.info.contractNumber,
          newContractCode:this.formInline.contractNumber,
          originalContractCode: this.info.originalContractCode?this.info.originalContractCode:this.info.contractNumber,
          updateDate: this.updateCurrentTime(),
          contractChangeTime: this.updateCurrentTime(),
          updateUser:localStorage.getItem('roleName'),
          relatedMerchants: this.info.relatedMerchants,
          tenantName: this.info.tenantName,
          tenantTelephone: this.info.tenantTelephone,
          shopNumber: this.info.shopNumber,
          templateInformationUrl:this.templateAttachment,
          createDate:this.updateCurrentTime(),
          createUser: localStorage.getItem('roleName'),
        }
        console.error(from)
        let info = await this.culfj()
        console.error(info)
        let c1 =  {
          documentAddress:  this.templateAttachment,
          insertData: JSON.stringify(info)
        }
        dataInprotDocument(c1).then(res => {
          console.error(res)
          if(res.code == 200 && res.data) {
            from.appendicesContract = res.data
            cereContractInformation(from).then(res => {
              console.error(res)
              if (res.code == 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                modifyResourceStatus({
                  resourcesId: info1.shopNumber,
                  status:"4"
                }).then(res => {
                  console.error(res)
                })
                if(this.dpinfo) {
                  cereAssetShopInformationedit({
                    ...this.dpinfo,
                    contractId:res.data
                  }).then(res => {
                    console.error(res)
                  })
                }
                this.$emit('removeonaction', '1')
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: '附件生成失败'
            })

          }
        })    

      },
      async add() {
        let ismb = false
        await this.$refs.rulesmbinfoForm.validate((valid) => {
          if (valid) {
            ismb = true
          } else {
            this.$message({
              message: '请填写完整信息',
              type: 'error'
            })
            ismb = false
          }
        })
        let isjx = await this.$refs.rulesallForm.yanzhen()
        console.error(ismb,isjx)
        if(ismb && isjx) {
          console.error(']]]]]')
          this.addinfo()
        }
      },
      close() {
        this.$emit('removeonaction', '1')
      },
      async addinfo(){
        let info1 = {}
        for (let index = 0; index < this.list1.length; index++) {
          const element = this.list1[index];
          console.error({...element})
          if(element.type == '资源') {
            if(element.value && typeof element.value == 'object') {
              if (element.value.shopName) {
                info1.shopNumber = 'sp' + element.value.id
              } else if (element.value.advertisingType) {
                info1.shopNumber = 'gg' + element.value.id
              } else {
                info1.shopNumber = 'cd' + element.value.id
              }
            }
          }else if(element.type == '商家') {
            info1.relatedMerchants = element.value
          } else{
            info1[element.key] = element.value+''
          }
          
        }
        console.error(info1)
        for (let key in info1) {
          if (this.formInline.hasOwnProperty(key)) {
            this.formInline[key] = info1[key];
          }
        }
        this.formInline.templateInformation = JSON.stringify(this.list1)
        let info = await this.culfj()
        console.error(info)
        let c1 =  {
          documentAddress:  this.templateAttachment,
          insertData: JSON.stringify(info)
        }
        dataInprotDocument(c1).then(res => {
          console.error(res)
          if(res.code == 200 && res.data) {
            this.formInline.appendicesContract = res.data
            contractinsertAdd({
              ...this.formInline,
              templateInformationUrl:this.templateAttachment,
              createDate:this.updateCurrentTime(),
              createUser: localStorage.getItem('roleName'),
              updateDate: this.updateCurrentTime(),
              updateUser:localStorage.getItem('roleName'),
            }).then(res => {
              console.error(res)
              if (res.code == 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                modifyResourceStatus({
                  resourcesId: info1.shopNumber,
                  status:"4"
                }).then(res => {
                  console.error(res)
                })
                if(this.info.id) {
                  if(this.info.cereBasicInformationShop && this.info.cereBasicInformationShop.id) {
                    msgedit({
                      auditStatus: '4',
                      id: this.info.id,
                      contractNumber: this.formInline.contractNumber
                    })
                  }
                  if(this.info.cereAdvertisingInformation && this.info.cereAdvertisingInformation.id) {
                    AdvertiserInfoEdit({
                      auditStatus: '4',
                      id: this.info.id,
                      contractId: this.formInline.contractNumber
                    }).then(item => {
                      this.getAll()
                    })
                  }
                  if(this.info.cereBasicInformationVenue && this.info.cereBasicInformationVenue.id) {
                    msgedit({
                      auditStatus: '4',
                      id: this.info.id,
                      contractNumber: this.formInline.contractNumber
                    })
                  }
                }
                this.$emit('removeonaction', '1')
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            })
          } else {
            this.$message({
              type: 'error',
              message: '附件生成失败'
            })

          }
        })
        console.error({...this.formInline})
      },
      async changeRelatedMerchants(e) {
        console.error(e)
        this.isshow = false
        this.templateAttachment = this.mbData[e].templateAttachment
        console.error(this.mbData[e])
        this.onmbinfo = this.mbData[e]
        //判断是否是字符串
        if (typeof this.mbData[e].otherInfo == 'string') {
          this.list1 = JSON.parse(this.mbData[e].otherInfo)
        } else {
          this.list1 = this.mbData[e].otherInfo
        }
        for (let i = 0; i < this.list1.length; i++) {
          if(this.list1[i].type == '资源'){
            if(this.AddData.length>0){
              this.list1[i].list = this.AddData
              this.list1[i].value = this.list1[i].list[0]
            }
          } else if(this.list1[i].type == '商家'){
            if(this.info.applicant) {
              await cerePlatformMerchant({
                checkState: '2',
                pageNumber: 0,
                pageSize: 1000,
                phone: this.info.applicant
              }).then(res => {
                console.error(res)
                this.list1[i].value = res.data.content.length>0?res.data.content[0].id+'':''
              })
            }
          }
        }
        //延迟2秒
        setTimeout(() => {
          this.isshow = true
        }, 100)
      },
      async getmb() {
        const res = await cereContractTemplate({ pageNumber: 0,pageSize: 100})
        this.mbData = res.data.content
      },
      async culfj(){
        let info = {}
        for (let index = 0; index < this.list1.length; index++) {
          const element = this.list1[index];
          // console.error({...element})
		  
          if(element.type == '资源') {
			  console.log(element.value,'element.value')
            if(element.value && typeof element.value == 'object') {
              info['资源名称'] =element.value.shopName?element.value.shopName:element.value.advertisingName?element.value.advertisingName:element.value.venueName?element.value.venueName:'暂无'
			  
              info['资源类型'] =element.value.shopName?'商铺':element.value.advertisingType?element.value.advertisingType:element.value.venueName?'场地':'暂无'
			  if(element.value.venueName){
				  info['详细地址'] ='暂无'
			  }else{
				info['详细地址'] = element.value.detailedLocation?element.value.detailedLocation:'暂无'  
			  }
              
              info['实际使用面积'] = element.value.actualArea?element.value.actualArea:element.value.actualUsableArea?element.value.actualUsableArea:'暂无'
            } else {
              info['资源名称'] = '暂无'
              info['资源类型'] = '暂无'
              info['详细地址'] = '暂无'
              info['实际使用面积'] = '暂无'
            }
          } else if(element.type == '商家') {
            if(element.value){
              await cerePlatformMerchant({
                checkState: '2',
                pageNumber: 0,
                pageSize: 1000,
                id: element.value
              }).then(res => {
                console.error(res)
                info['商家'] = res.data.content.length>0?res.data.content[0].name:'暂无'
              })
            } else {
              info['商家'] = '暂无'
            }
            
          } else{
            info[element.name] = element.value?element.value+'':'暂无'
          }
          
        }
		
        return info
      },
      async ylht(){
        let info = await this.culfj()
        console.error(info)
        let c1 =  {
          documentAddress:  this.templateAttachment,
          insertData: JSON.stringify(info)
        }
        dataInprotDocument(c1).then(res => {
          console.error(res)
          if(res.code == 200 && res.data) {
            this.openfile(this.$baseURL+res.data)
          } else {
            this.$message({
              type: 'error',
              message: '预览失败'
            })

          }
        })
      },
      openfile(e) {
        if (e) {
          const fullUrl = e;
          try {
            window.open(fullUrl, '_blank'); // 在新标签页中打开文件
          } catch (error) {
            console.error('打开文件失败:', error);
          }
        } else {
          console.error('无文件可查看');
        }
      },
      async mingShow() {
        this.addzy = true
      },
        //获取当前时间
      updateCurrentTime() {
          const now = new Date();
          const year = now.getFullYear();
          const month = (now.getMonth() + 1).toString().padStart(2, '0');
          const day = now.getDate().toString().padStart(2, '0');
          const hours = now.getHours().toString().padStart(2, '0');
          const minutes = now.getMinutes().toString().padStart(2, '0');
          const seconds = now.getSeconds().toString().padStart(2, '0');

          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
    }
  }
</script>
<style lang="css">
  .el-upload {
    display: block;
    text-align: left;
  }

  .el-dialog__header {
    background-color: #F2F3F5;
    text-align: left;
  }

  .el-dialog__title {
    line-height: 30px;
    font-size: 15px;
    color: #303133;
  }

  .iterem {
    z-index: 99;
    margin-left: 10px;
    height: 40px;
    line-height: 25px;
  }
</style>
