<template>
  <div>
    <el-form :model="formInline" :rules="rulesHetong" ref="heForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="招商方案名称" class="grid-content bg-purple device-from" prop="planName">
        <el-input v-model="formInline.planName" placeholder="请输入" maxlength="100" />
      </el-form-item>
      <el-form-item label="招商政策与条件" class="grid-content bg-purple" prop="investmentPolicy">
        <wang-editor v-model="formInline.investmentPolicy" ref="editor" :height="200"></wang-editor>
      </el-form-item>
      <el-form-item label="方案概述" prop="summary" class="grid-content bg-purple">
        <wang-editor v-model="formInline.summary" ref="editor" :height="200"></wang-editor>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="招商资源管理" prop="shopNumber">
            <div style="border: 1px solid #E5E5E5;padding: 1px" id="huodong">
              <div
                style="font-size: 14px;border-bottom: 1px solid #E5E5E5;display: flex;justify-content: space-between;line-height:20px;background:#F2F3F5;">
                <div></div>
                <div style="color: #3F9B6A;padding:10px;" @click="mingShow">
                  添加
                </div>
              </div>
              <div style="padding: 15px;">
                <div style="padding: 0px 20px 0px 0px">
                  <el-table :data="AddData" :span-method="tableSpanMethod"
                    :header-cell-style="{fontSize: '14px',color:'#0009',fontWeight: 'normal',backgroundColor:'#F2F3F5'}">
                    <el-table-column label="序号" min-width="50" prop="one">
                      <template slot-scope="scope">
                        {{scope.$index + 1}}
                      </template>
                    </el-table-column>
                    <el-table-column label="资源名称"  prop="name"   show-overflow-tooltip>
                      <template slot-scope="scope">
                        {{scope.row.zyinfo.shopName ? scope.row.zyinfo.shopName :  scope.row.zyinfo.advertisingName?scope.row.zyinfo.advertisingName:scope.row.zyinfo.venueName}}
                      </template>
                    </el-table-column>
                    <el-table-column label="资源类型" prop="type" >
                      <template slot-scope="scope">
                        {{scope.row.zyinfo.shopName ? '商铺' : scope.row.zyinfo.advertisingType?scope.row.zyinfo.advertisingType:'场地'}}
                      </template>
                    </el-table-column>
                    <el-table-column label="策略名称" >
                      <template slot-scope="scope">
                        {{scope.row.clinfo.policyName || '-'}}
                      </template>
                    </el-table-column>
                    <el-table-column label="策略描述" >
                      <template slot-scope="scope">
                        {{scope.row.clinfo.policyName || '-'}}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" prop="cz" >
                      <template slot-scope="scope">
                        <div v-if="scope.row.num == 1" @click="opencl(scope.row.zyinfo)" class="tableBtn greens">策略选择</div>
                        <div @click="removezy(scope.row.zyinfo)" class="tableBtn greens">编辑</div>
                        <div @click="MingDelete(scope.row.zyinfo)" class="tableBtn greens">删除</div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="附件信息" prop="attachmentInfo">
        <upfile :accept="'.docx,.doc'" filePath="fa" inputtype="attachmentInfo" :value="formInline.attachmentInfo" @changimg="e=>changimg(e,'attachmentInfo')"></upfile>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item>
            <div style="margin-top: 20px">
              <el-button @click="add()" style="background-color: #3F9B6A;color: #fff;">确定</el-button>
              <el-button @click="close()" class="buttonHover"
                style="color: #606266;border: 1px solid #DBDBDB;background-color: #fff;">取消</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog :visible.sync="addMing" title="选择资源" style="padding: 0;" width="65%" append-to-body center
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <zy v-if="addMing" @mingClose="mingClose" @minSev="minSev"></zy>
        
      
    </el-dialog>
    <el-dialog :visible.sync="onaction" title="编辑" style="padding: 0;" width="65%" append-to-body center
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="height: 40vh;overflow-y: scroll;">
        <div v-if="ontype == '1'" style="padding: 20px 20px 20px 0;">
          <add :info="detailsinfo" @removeonaction="removeonaction"></add>
        </div>
        <div v-if="ontype == '2'" style="padding: 20px 20px 20px 0;">
          <addmap :info="detailsinfo" @removeonaction="removeonaction"></addmap>
        </div>
        <div v-if="ontype == '3'" style="padding: 20px 20px 20px 0;">
          <addcd :info="detailsinfo" @removeonaction="removeonaction"></addcd>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="addcl" title="选择策略" width="65%" append-to-body center :close-on-click-modal="false"
      :close-on-press-escape="false" :show-close="false">
      <cl :resourcesId="oncetype+oninfo.id" v-if="addcl" @minSev="minSevcl" @mingClose="mingClosecl"></cl>
    </el-dialog>
  </div>
</template>

<script>
  import zy from "@/components/change/zy"
  import upfile from "@/components/fujianUpload/fujianList"
  import upimg from "@/components/ImageUpload/index"
  import wangEditor from "@/components/editor/index";
  import addmap from '@/components/add/addmap'
  import addcd from '@/components/add/addcd'
  import add from '@/components/add/addinformation'
   import cl from '@/components/change/cl.vue'
  import {
    fangAdd,
    fangEdit,
  } from '@/api/fangli';
  import {
    cereResourceStrategy,
    cereBusinessOperationadd,
    modifyResourceStatus,
    cereBusinessPlanqueryById
  } from '@/api/newly.js'
  export default {
    components: {
      addcd,
      addmap,
      add,
      upimg,
      wangEditor,
      upfile,
      zy,
      cl
    },
    data() {
      return {
        multipleSelection: [],
        oninfo:{},
        oncetype:'',
        addcl:false,
        detailsinfo:{},
        ontype:'1',
        onaction:false,
        AddData: [], //选中的资源
        addMing: false,
        formInline: {
          planName: '',
          planningScheme: '',
          investmentPolicy: '',
          summary: '',
          financialAnalysis: '',
          attachmentInfo: '',
          resourceManagement: '',
          auditStatus: '1'
        },
        rulesHetong: {
          planName: [{
            required: true,
            message: '请填写招商方案名称',
            trigger: 'change'
          }],
        },
      };
    },
    props: {
      info: {
        type: Object,
        default: {}
      }
    },
    async created() {
      if (this.info && this.info.id) {
        this.formInline = this.info
        console.error({...this.formInline})
        cereBusinessPlanqueryById({id:this.formInline.id}).then(res => {
          let c1 = []
          for (let index = 0; index < res.data.resourceList.length; index++) {
            const element = res.data.resourceList[index];
            if (element.cereBasicInformationShop.id) {
              for (let i = 0; i < element.cereRentalPolicies.length; i++) {
                var element1 = element.cereRentalPolicies[i];
                let info = {
                  cnet:'sp'+element.cereBasicInformationShop.id,
                  zyinfo:element.cereBasicInformationShop,
                  num:element.cereRentalPolicies.length,
                  clinfo:element1
                }
                c1.push(info);
              }
            }
            if (element.cereAdvertisingInformation.id) {
              for (let i = 0; i < element.cereRentalPolicies.length; i++) {
                var element1 = element.cereRentalPolicies[i];
                let info = {
                  cnet:'gg'+element.cereAdvertisingInformation.id,
                  zyinfo:element.cereAdvertisingInformation,
                  num:element.cereRentalPolicies.length,
                  clinfo:element1
                }
                c1.push(info);
              }
            }
            if (element.cereBasicInformationVenue.id) {
              for (let i = 0; i < element.cereRentalPolicies.length; i++) {
                var element1 = element.cereRentalPolicies[i];
                let info = {
                  cnet:'cd'+element.cereBasicInformationVenue.id,
                  zyinfo:element.cereBasicInformationVenue,
                  num:element.cereRentalPolicies.length,
                  clinfo:element1
                }
                c1.push(info);
              }
            }
          }
          console.error(c1)
          this.AddData = c1
        })
      } else {

      }
    },
    methods: {
      minSevcl(e) {
        this.multipleSelection = e
        // console.error(this.multipleSelection)
        let listall = []
        for (let n = 0; n < this.AddData.length; n++) {
          const element = this.AddData[n];
          let cnet = ''
          if (element.zyinfo.shopName) {
            cnet = 'sp' + element.zyinfo.id
          } else if (element.zyinfo.advertisingType) {
            cnet = 'gg' + element.zyinfo.id
          } else {
            cnet = 'cd' + element.zyinfo.id
          }
          if (this.oninfo.id == element.zyinfo.id) {
            for (let index = 0; index < this.multipleSelection.length; index++) {
              let info = {
                cnet:cnet,
                zyinfo:element.zyinfo,
                num:this.multipleSelection.length,
                clinfo:this.multipleSelection[index]
              }
              listall.push(info)
            }
          } else{
            listall.push(this.AddData[n])
          }
        }
        this.AddData = listall
        
        this.addcl = false
      },
      mingClosecl() {
        this.multipleSelection = []
        this.addcl = false
      },
      async opencl(row) {
        if (row.shopName) {
          this.oncetype = 'sp'
        } else if (row.advertisingType) {
          this.oncetype = 'gg'
        } else {
          this.oncetype = 'cd'
        }
        this.oninfo = row
        this.multipleSelection = []
        this.addcl = true
      },
      removeonaction() {
        this.onaction = false
      },
      removezy(row) {
        if (row.shopName) {
          this.ontype = '1'
        } else if (row.advertisingType) {
          this.ontype = '2'
        } else {
          this.ontype = '3'
        }
        this.detailsinfo = row
        this.onaction = true
      },
      changimg(e, type) {
        this.formInline[type] = e
      },
      addclall (id,ids) {
        let c1 = {
          resourcesId: id,
          rentalPoliciesIds: ids,
        }
        console.error(c1)
        cereResourceStrategy(c1).then(res => {
          if (res.code == 200) {
          } else {
            this.$message({
              message: '绑定失败',
              type: 'error'
            })
          }
        })
      },
      async clinfo() {
        let c2 = ''
        let alllist = this.buildTree(this.AddData)
        console.error(alllist)
        //判断alllist是不是数组
        if (Array.isArray(alllist)) {
          for (let i = 0; i < alllist.length; i++) {
            console.error(alllist[i])
            let cnet = alllist[i].id
            alllist[i].clids = alllist[i].clids +''
            await this.addclall(alllist[i].id,alllist[i].clids.split(","))
            if (i == 0) {
              c2 = cnet
            } else {
              c2 = c2 + ',' + cnet
            }
          }
          
        } else{
          return
        }
        console.error(c2)
        
        await cereBusinessOperationadd({
          type: '发布',
          resourceId: c2,
          operator: localStorage.getItem('roleName'),
          operationTime: this.gettime()
        }).then(res => {
          console.error(res)
        })
        this.formInline.resourceManagement = c2
        console.error({
          ...this.formInline
        })
        
        // return
        if(this.formInline.id) {
          this.formInline.updateTime = this.updateCurrentTime()
          this.formInline.updateUser = localStorage.getItem('roleName')
          fangEdit({
            ...this.formInline
          }).then(res => {
            console.error(res)
            if (res.code == 200) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              modifyResourceStatus({
                resourcesId: c2,
                  status:"1"
              }).then(res => {
                console.error(res)
              })
              this.$emit('removeonaction', '1')
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }

          })
        } else {
          this.formInline.createTime = this.updateCurrentTime()
          this.formInline.createUser = localStorage.getItem('roleName')
          fangAdd({
            ...this.formInline
          }).then(res => {
            console.error(res)
            if (res.code == 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              modifyResourceStatus({
                resourcesId: c2,
                  status:"1"
              }).then(res => {
                console.error(res)
              })
              this.$emit('removeonaction', '1')
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }

          })
        }
      },
      async add() {
        this.$refs.heForm.validate((valid) => {
          console.log(valid)
          if (valid) {
            if(this.AddData.length == 0) {
              this.$message({
                message: '请选择招商资源',
                type: 'error'
              })
              return
            }
            this.clinfo()
          } else {
            this.$message({
              message: '请填写完整信息',
              type: 'error'
            })
            return false;
          }
        })
      },
            //获取当前时间
      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}`;
      },

      close() {
        this.$emit('removeonaction', '1')
      },
      MingDelete(item) {
        // this.AddData.splice(item, 1);
        let array = JSON.parse(JSON.stringify(this.AddData));
        for (let index = 0; index < array.length; index++) {
          const element = array[index];
          if (element.zyinfo.id == item.id) {
            this.AddData.splice(index, element.num);
          }
        }
      },
      async mingShow() {
        this.addMing = true
      },
      minSev(e) {
        // console.error(e)
        let list = []
        let filteredAddData = []
        if(this.AddData.length>0) {
          filteredAddData = e.filter(item => {
            let isExist = true;
            this.AddData.filter(itemAdd => {
              if(itemAdd.zyinfo.id == item.id) {
                isExist = false
              } 
            });
            if(isExist) {
              return item;
            }
          });

        } else {
          filteredAddData = e
        }
        // console.error(filteredAddData)
        for (let index = 0; index < filteredAddData.length; index++) {
          const element = filteredAddData[index];
          let cnet = ''
          if (element.shopName) {
            cnet = 'sp' + element.id
          } else if (element.advertisingType) {
            cnet = 'gg' + element.id
          } else {
            cnet = 'cd' + element.id
          }
          let info = {
            zyinfo:element,
            num:1,
            cnet:cnet,
            clinfo:{
              
            }
          }
          list.push(info)
        }
        this.AddData = this.AddData.concat(list)
        
        this.addMing = false
      },
      mingClose() {
        this.addMing = false
      },
      tableSpanMethod({ row, column, rowIndex }) {
        if (["name", "type","one","cz"].includes(column.property)) {
          // 判断 num 是否相同，合并行
          const num = row.num;
          const cnet = row.cnet;
          const startRowIndex = this.findStartRowIndex(rowIndex, num,cnet);
          
          return startRowIndex === rowIndex 
            ? { rowspan: num, colspan: 1 } 
            : { rowspan: 0, colspan: 0 };
        }
      },
      findStartRowIndex(rowIndex, num,cnet) {
        let startRowIndex = rowIndex;
        for (let i = rowIndex - 1; i >= 0; i--) {
          if (this.AddData[i].num === num && this.AddData[i].cnet === cnet) {
            startRowIndex = i;
          } else {
            break;
          }
        }
        return startRowIndex;
      },
      buildTree(clinfoArray) {
        let list = [];
        for (let index = 0; index < clinfoArray.length; index++) {
          const element = clinfoArray[index];
          if(list.length>0) {
            let c1 = true
            for (let n = 0; n < list.length; n++) {
              const item = list[n];
              if(item.id == element.cnet) {
                c1 = false
              } else {
                
              }
           }
           if(c1) {
              let info ={
                id: element.cnet,
                children:[],
                clids:''
              }
              for (let i = 0; i < clinfoArray.length; i++) {
                const elementnew = clinfoArray[i];
                if(elementnew.cnet == info.id) {
                  info.children.push(elementnew)
                  if(elementnew.clinfo && elementnew.clinfo.id) {
                    if(i == 0) {
                      info.clids = elementnew.clinfo.id+''
                    } else {
                      info.clids = info.clids + ','+elementnew.clinfo.id
                    }
                  } else {
                    this.$message({
                      message: '资源请绑定策略',
                      type: 'error'
                    })
                    return false;
                  }
                }
                
              }
              list.push(info)
           }
          } else {
            let info ={
                id: element.cnet,
                children:[],
                clids:''
              }
              for (let i = 0; i < clinfoArray.length; i++) {
                const elementnew = clinfoArray[i];
                if(elementnew.cnet == info.id) {
                  info.children.push(elementnew)
                  if(elementnew.clinfo && elementnew.clinfo.id) {
                    if(i == 0) {
                      info.clids = elementnew.clinfo.id
                    } else {
                      info.clids = info.clids + ','+elementnew.clinfo.id
                    }
                  } else {
                    this.$message({
                      message: '资源请绑定策略',
                      type: 'error'
                    })
                    return false;
                  }
                }
                
              }
              list.push(info)
          }
        }
        return list
      },
      gettime() {
        // 获取当前时间
        let currentTime = new Date();

        // 获取年份
        let year = currentTime.getFullYear();

        // 获取月份（注意月份是从0开始计数的，所以需要加1）
        let month = currentTime.getMonth() + 1;

        // 获取日期
        let day = currentTime.getDate();

        // 获取小时
        let hours = currentTime.getHours();

        // 获取分钟
        let minutes = currentTime.getMinutes();

        // 获取秒数
        let seconds = currentTime.getSeconds();

        // 获取毫秒数
        let milliseconds = currentTime.getMilliseconds();

        // 格式化时间为 YYYY-MM-DD
        let formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

        // 格式化时间为 HH:MM:SS
        let formattedTime =
          `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        // 格式化时间为 YYYY-MM-DD HH:MM:SS
        let formattedDateTime = `${formattedDate} ${formattedTime}`;
        return formattedDateTime

      },
    },
  };
</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;
  }
</style>
