<template>
    <div>

        <div class="dialog-h-content scroll-h">
            <el-form ref="ref_form" :inline="true" :model="formData" :rules="dataRule" :disabled="formType === 'detail'"
                class="form">
                <el-form-item label="文章标题" prop="title" label-width="150px">
                    <el-input v-model.trim="formData.title" size="small" clearable placeholder="请输入活动名称"
                        class="u-item-width-normal"></el-input>
                </el-form-item>

                <el-form-item label="发布时间" label-width="140px" prop="releaseTime">
                    <el-date-picker v-model.trim="formData.releaseTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                        format="yyyy-MM-dd HH:mm:ss" placeholder="选择发布时间" style="width:280px">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="文章标签" prop="tagId" label-width="150px" >
                    <el-select class="u-item-width-normal" v-model.trim="formData.tagId" placeholder="请选择" clearable>
                        <el-option v-for="item in adverTagList" :key="item.id" :label="item.tagName" :value="item.id"
                            class="u-item-width-normal">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="封面图片" label-width="140px" prop="coverPic">
                    <template>
                        <upload-image :defaultFileList="fileList" :limit="1" @file-removed="handleFileRemoved" @change="onChangeFileList"></upload-image>
                    </template>
                </el-form-item>

                <el-form-item label="内容" prop="content" label-width="150px" style="display: block">
                    <div class="item_width_1">
                        <Tinymce class="tinymce_view " v-if="formType != 'detail'" v-model.trim="formData.content"
                            :height="250" placeholder="在这里输入文字" />
                    </div>
                </el-form-item>

                <el-form-item label="首页置顶" style="display: block" prop="top" label-width="150px">
                    <el-switch v-model="formData.top" @change="handleOnlineRegistration"></el-switch>
                </el-form-item>

                <el-form-item label="消息推送" label-width="140px" prop="sendMsg">
                        <el-checkbox v-model="formData.sendMsg"   @change="checkbox1" label="是否通过公众号推送给社区居民"></el-checkbox>
                </el-form-item>
            </el-form>
        </div>

        <div class="div_btn">
            <el-button size="small" @click="handleCancle">取 消</el-button>
            <el-button size="small" type="primary" :disabled="btnDisable" @click="handleComfirm">确
                定</el-button>
        </div>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import Tinymce from '@c/tinymce2/index.vue'
import daiMap from "@/utils/dai-map";
import util from '@js/util.js';
// import UploadImage from './upload-image.vue'
import UploadImage from '@/views/modules/plugins/rent/upload-image.vue'

var map
var search
var markers
var infoWindowList
var geocoder // 新建一个正逆地址解析类

let loading // 加载动画
export default {
  data() {
    //   let initFormData = () => {
    //       let _form = {
    //         title: "",//标题
    //         content: "",//内容
    //         tagId: "",//标签id
    //         coverPic: "",//封面图
    //         releaseTime: "",//发布时间
    //         sendMsg: 0,//是否推送
    //         top: 0,//是否置顶
    //         status: 0 //状态
      
    //       }

    //       return _form
    //   }
      return {
        adverTagList:[],
        //////
          top:false,
          fileList: {},//封面图片
          activityImgs:[],//活动照片
          formType: 'add', //表单操作类型 add新增，edit编辑,records记录
        //   records:false,
          searchOptions: [],
          searchValue: '',
          resultList: [],
          num: 0,
          loading: false,
          timeRange: [],
          online: false,

          btnDisable: false,

          keyWords: '',
          activityId: '',
          formData: {   
            title: "",//标题
            content: "",//内容
            tagId: "",//标签id
            coverPic: "",//封面图
            releaseTime: "",//发布时间
            sendMsg: false,//是否推送
            top: false,//是否置顶
            status: 0 //状态
        },
          serviceList: [],
        //   gridList: [],
          agencyId: '',
          agencyName:"",
          releaseTime: '',

          demandOptions: [],
          uploadUrl: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
          customerId: localStorage.getItem('customerId'),

      }
  },
  components: { Tinymce, UploadImage },
  mounted() {
    this.agencyName=this.$store.state.user.agencyName,
    this.agencyId=this.$store.state.user.agencyId,
    this.advertisingTag()
    this.setDefaultReleaseTime();
      
  },

  methods: {
    checkbox1(val){
        console.log(val);
    },
    handleFileRemoved(file) {
      // 处理从子组件接收到的删除文件的信息
      console.log('File removed:', file);
      this.formData.coverPic=""
      // 例如，可以在这里更新父组件的文件列表或执行其他操作
    },

    // 获取广告标签
    advertisingTag(){
        requestPost('/advertisingTag/list',{customerId:this.customerId}).then(res=>{
            console.log(res,'res');
            
            if(res.code==0){
                this.adverTagList=res.data
            }
        })
    },
    // 获取广告标签
    advertisingTag(){
    },
    async initForm(typeid,row) {
            this.startLoading();
            if(row!=null){
                 this.formData = JSON.parse(JSON.stringify(row));
                 console.log(this.formData.coverPic);
             
            }
            this.formType=typeid
            console.log(this.formData,"5164");
            this.endLoading();
            this.setDefaultReleaseTime()
        },
    async advertisingTag () {
          const url = "/actual/base/advertisingTag/page"
          let params = {
            pageSize: this.pageSize,
            pageNo: this.pageNo,
            tagName: "",
            status: ""
          }
          const { data, code, msg,internalMsg } = await requestPost(url, params)
          if (code === 0) {
            this.adverTagList = data.list
          } else if(internalMsg !== ''){
            this.$message.error(internalMsg)
          }else {
            this.$message.error(msg)
          }
        },
      handleOnlineRegistration(value) {
          console.log(this.fileList);
          if( value && this.fileList.length==0){
            console.log("51545");
            this.$message.error("置顶需上传封面图片")
            this.formData.top = false;
            
            
          }
      },

      onChangeFileList(e) {
        this.fileList = e.length > 0 ? e.map(item => ({
                fileType: '0',
                fileUrl: item.response.data.url
            })) : []; // 当e为空时清空fileList
        console.log(e,'e');
          if (e.length > 0) {
              let item = e[0];
              let ob = {
                  fileType: '0',
                  fileUrl: item.response.data.url
              };
              this.fileList = [ob];
              this.formData.coverPic = ob.fileUrl;
          }else {
                this.formData.coverPic = '';
            }
          
      },

    //   async initForm(type, activityId) {
    //       this.startLoading()
    //       this.formType = type
    //     //   console.log("阿斯顿撒打算",type, activityId)
    //       if (type === 'edit') {
    //           this.formData = activityId
    //           if (activityId.coverPic) {
    //               let ob = {
    //                   fileType: '0',
    //                   fileUrl: activityId.coverPic
    //               };
    //               this.fileList = [ob];
    //               this.formData.coverPic = ob.fileUrl;
    //               if(this.formData.top == 1){
    //                   this.top = true
    //               }
    //           }
    //         //   console.log("this.fileList",this.fileList)
    //       }else if (type === 'records') {
    //           this.records = true
    //       }
          
    //       this.endLoading()

    //   },

      async handleComfirm() {
          this.btnDisable = true
          setTimeout(() => {
              this.btnDisable = false
          }, 10000)

          this.$refs['ref_form'].validate((valid, messageObj) => {
            this.formData.agencyName= this.agencyName
            this.formData.agencyId= this.agencyId
            this.formData.status= 0
            console.log("this.formData看看里面村的什么",this.formData)
            if (!valid) {
              app.util.validateRule(messageObj)
              this.btnDisable = false
            } else {

              this.addActivity()
            }
          })
      },
      async addActivity() {
          if (this.formType === 'edit') {
              let url = '/actual/base/communityPublicity/update'
              this.formData.sendMsg= this.formData.sendMsg? 1:0
              this.formData.top= this.formData.top? 1:0
                console.log(this.formData.top);
              console.log(this.formData,"formData");
              const { data, code, msg } = await requestPost(url, this.formData)
              if (code === 0) {
                  this.$message({
                      type: 'success',
                      message: '操作成功'
                  })
                  this.resetData()
                  this.$emit('dialogOk')
                  this.btnDisable = false
              } else {
                  this.btnDisable = false
                  this.$message.error(msg)
              }
          }else{
              console.log("this.formData",this.formData)
              let url = '/actual/base/communityPublicity/save'
              console.log(this.formData,"formData");
              this.formData.sendMsg= this.formData.sendMsg? 1:0
              this.formData.top= this.formData.top? 1:0
              const { data, code, msg } = await requestPost(url, this.formData)
              if (code === 0) {
                  this.$message({
                      type: 'success',
                      message: '操作成功'
                  })
                  this.resetData()
                  this.$emit('dialogOk')
                  this.btnDisable = false
              } else {
                  this.btnDisable = false
                  this.$message.error(msg)
              }
          }
          

      },

      handleCancle() {
          this.resetData()
          this.$emit('dialogCancle')

      },

      resetData() {
          this.fileList = []
          this.top = 0
          this.formType = ''
          this.formData = {

          }

      },
      // 开启加载动画
      startLoading() {
          loading = Loading.service({
              lock: true, // 是否锁定
              text: '正在加载……', // 加载中需要显示的文字
              background: 'rgba(0,0,0,.7)' // 背景颜色
          })
      },
      // 结束加载动画
      endLoading() {
          // clearTimeout(timer);
          if (loading) {
              loading.close()
          }
      },
      setDefaultReleaseTime() {
      const currentDate = new Date();
      const formattedDate = this.formatDate(currentDate, 'yyyy-MM-dd HH:mm:ss');
      this.formData.releaseTime = formattedDate;
    },
    formatDate(date, format) {
      const pad = (n) => (n < 10 ? '0' + n : n);
      const year = date.getFullYear();
      const month = pad(date.getMonth() + 1);
      const day = pad(date.getDate());
      const hours = pad(date.getHours());
      const minutes = pad(date.getMinutes());
      const seconds = pad(date.getSeconds());
      return format
        .replace('yyyy', year)
        .replace('MM', month)
        .replace('dd', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    }
  
  },
  computed: {
      dataRule() {
          return {
            title: [
                  { required: true, message: '文章标题不能为空', trigger: 'blur' }
              ],
 
              content: [
                  { required: true, message: '内容不能为空', trigger: 'blur' }
              ],
              releaseTime: [
                  { required: true, message: '请选择发布时间', trigger: 'blur' }
              ],
              tagId: [
                  { required: true, message: '请选择文章标签', trigger: 'blur' }
              ],
        
          }
      },

  },
  props: {
      // unitList: {
      //     type: Array,
      //     default: []
      // },
      //   gridList: {
      //       type: Array,
      //       default: []
      //   },
  }
}
</script>


<style lang="scss" scoped>
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
<style lang="scss" scoped>
.item_width_1 {
  width: 560px;

  /deep/.tox .tox-dialog {
      z-index: 20000;
  }
}

.tinymce_view {
  ::v-deep .tox .tox-dialog {
      z-index: 2000000000;
  }
}

.div_map {
  position: relative;
}

.div_searchmap {
  z-index: 5000;
  position: absolute;
  top: 5px;
  left: 5px;
}

.tinymce_view {
  height: 400px;
  overflow: auto;
}

.text_p {
  margin: 0;
  padding: 0 10px;
  border: 1px solid #d9d9d9;
  border-radius: 5px;

  >p {
      margin: 0;
  }
}
</style>