<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" :title="type === 'add' ? '新增活动' : '编辑活动'" :form="form" :rules="rules" @submit="submit">
      <template v-slot:activeName>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.activeName" placeholder="请输入活动名称" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:company_ids>
        <div class="xy-table-item">
          <div class="xy-table-item-label">活动关联方：</div>
          <div class="xy-table-item-content">
            <Button
              type="primary"
              icon="md-add"
              style="margin-bottom: 10px"
              @click="form.company_ids.push({ type_id: '',type_name:'', company_id: '',name:'' })"
              >新增</Button
            >
            <xy-table
              style="width: 620px"
              :height="260"
              :is-page="false"
              :list="form.company_ids"
              :table-item="contentTable"
            >
              <template v-slot:btns>
                <el-table-column
                  label="操作"
                  width="90"
                  header-align="center"
                  align="center"
                >
                  <template v-slot:default="scope">
                    <Button
                      size="small"
                      type="primary"
                      ghost
                      @click="form.company_ids.splice(scope.$index, 1)"
                      >删除</Button
                    >
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>
      <template v-slot:fields>
        <div class="xy-table-item">
          <div class="xy-table-item-label">活动提交字段：</div>
          <div class="xy-table-item-content">
            <Button
              type="primary"
              icon="md-add"
              style="margin-bottom: 10px"
              @click="form.fields.push({ name: '',filed:'', is_reqired: '',data_name:'',data_id:'' })"
              >新增</Button
            >

            <xy-table
              style="width: 620px"
              :height="260"
              :is-page="false"
              :list="form.fields"
              :table-item="fieldsTable"
            >
              <template v-slot:btns>
                <el-table-column
                  label="操作"
                  width="90"
                  header-align="center"
                  align="center"
                >
                  <template v-slot:default="scope">
                    <Button
                      size="small"
                      type="primary"
                      ghost
                      @click="form.fields.splice(scope.$index, 1)"
                      >删除</Button
                    >
                  </template>
                </el-table-column>
              </template>
            </xy-table>
          </div>
        </div>
      </template>
      <!-- <template v-slot:shopId>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>发布方：
          </div>
          <div class="xy-table-item-content">
            <el-input readonly v-model="form.shopId.label" placeholder="请选择发布方" clearable style="width: 300px; " @focus="isShowShops = true,getCompanys()">
              <i
                class="el-icon-arrow-down el-input__icon"
                slot="suffix"
                @click="isShowShops = true,getCompanys()">
              </i>
            </el-input>
          </div>
        </div>
      </template>
      <template v-slot:sponsor>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>主办方：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.sponsor" placeholder="请输入主办方" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template> -->
      <template v-slot:sponsorLogo>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            主办方logo：
          </div>
          <div class="xy-table-item-content">
            <div v-if="form.sponsorLogo" style="position: relative;">
              <img :src="form.sponsorLogo" class="avatar">
              <Button
                shape="circle"
                icon="md-close"
                type="error"
                size="small"
                class="img__delete"
                @click="form.sponsorLogo = ''"></Button>
            </div>
            <el-upload
              v-else
              accept="picture"
              :limit="1"
              class="avatar-uploader"
              list-type="picture-card"
              :action="action"
              :show-file-list="true"
              :on-error="uploadFail"
              :on-success="uploadSuccess"
              :before-upload="uploadBefore">
              <i  class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:sponsorAdvertise>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            主办方广告语：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.sponsorAdvertise" placeholder="请输入主办方广告语" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:recommend>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            简介：
          </div>
          <div class="xy-table-item-content">
            <el-input :autosize="{minRows:2}" type="textarea" v-model="form.recommend" placeholder="请输入简介" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>

      <template v-slot:lecturer>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            讲师：
          </div>
          <div class="xy-table-item-content">
            <el-input type="text" v-model="form.lecturer" placeholder="请输入讲师" clearable style="width: 300px;"></el-input>

          </div>
        </div>
      </template>
      <template v-slot:active_tag>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            活动信息位置：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width: 300px;" v-model="form.active_tag" placeholder="请选择">
                <el-option
                  v-for="item in [{value:'上',label:'上'},{value:'下',label:'下'}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </div>
        </div>
      </template>
      <template v-slot:active_type_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
           <span style="color: red;font-weight: 600;padding-right: 4px;">*</span> 活动分类：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width: 300px;" v-model="form.active_type_id" placeholder="请选择">
                <el-option
                  v-for="item in activeTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
          </div>
        </div>
      </template>
      <template v-slot:template>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            活动模板：
          </div>
          <div class="xy-table-item-content">
            <el-select style="width: 300px;" v-model="form.template" placeholder="请选择">
                <el-option
                  v-for="item in [{value:'旧',label:'旧'},{value:'新',label:'新'}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </div>
        </div>
      </template>
      <template v-slot:date>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker
              align='center'
              style="width: 360px;"
              v-model="form.date"
              value-format="yyyy-MM-dd/HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:applyDate>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>预约报名日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker
              align='center'
              style="width: 360px;"
              v-model="form.applyDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:address>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动地址：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.address" placeholder="请输入活动地址" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:relationName>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>联系人：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.relationName" placeholder="请输入联系人" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:phoneNumber>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>联系电话：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:group>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            活动人群：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.group" placeholder="请输入活动人群" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:memberSum>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            总活动人数：
          </div>
          <div class="xy-table-item-content">
            <el-input-number :precision="0" :controls="false" v-model="form.memberSum" placeholder="请输入活动人数" clearable style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>
      <template v-slot:startMemberSum>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            初始活动人数：
          </div>
          <div class="xy-table-item-content">
            <el-input-number :precision="0" :controls="false" v-model="form.startMemberSum" placeholder="请输入初始活动人数" clearable style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>
      <template v-slot:greatServices>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            服务亮点：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.greatServices" placeholder="请输入服务亮点" clearable style="width: 300px;"></el-input>
          </div>
        </div>
      </template>
<!--      <template v-slot:money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            活动金额：
          </div>
          <div class="xy-table-item-content">
            <el-input-number :precision="2" :controls="false" v-model="form.money" placeholder="请输入活动金额" clearable style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template> -->
      <template v-slot:activePlaybill>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动海报：
          </div>
          <div class="xy-table-item-content">
            <div v-if="form.activePlaybill" style="position: relative;">
              <img :src="form.activePlaybill" class="avatar">
              <Button
                shape="circle"
                icon="md-close"
                type="error"
                size="small"
                class="img__delete"
                @click="form.activePlaybill = ''"></Button>
            </div>
            <el-upload
              v-else
              accept="picture"
              :limit="1"
              class="avatar-uploader"
              list-type="picture-card"
              :action="action"
              :show-file-list="true"
              :on-error="uploadFail"
              :on-success="uploadSuccess1"
              :before-upload="uploadBefore">
              <i  class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:illustration>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>插图：
          </div>
          <div class="xy-table-item-content">
            <div v-if="form.illustration" style="position: relative;">
              <img :src="form.illustration" class="avatar">
              <Button
                shape="circle"
                icon="md-close"
                type="error"
                size="small"
                class="img__delete"
                @click="form.illustration = ''"></Button>
            </div>
            <el-upload
              v-else
              accept="picture"
              :limit="1"
              class="avatar-uploader"
              list-type="picture-card"
              :action="action"
              :show-file-list="true"
              :on-error="uploadFail"
              :on-success="uploadSuccess2"
              :before-upload="uploadBefore">
              <i  class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:sort>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            排序：
          </div>
          <div class="xy-table-item-content">
            <el-input-number :precision="0" :controls="false" v-model="form.sort" placeholder="请输入排序" clearable style="width: 300px;"></el-input-number>
          </div>
        </div>
      </template>
      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>活动内容:
          </div>
          <div class="xy-table-item-content" style="width: 680px;">
            <xyTinymce v-if="isShow" :height="200" v-model="form.content"></xyTinymce>
          </div>
        </div>
      </template>
    </xy-dialog>

<!--    shopId选择-->
    <Modal v-model="isShowShops" title="关联方选择">
      <div class="searchCompanys">
        <el-input type="text" @keyup.enter.native="getCompanys" v-model="companykeyword" placeholder="请输入关键词查找商户"></el-input>
        <el-button type="primary" @click="getCompanys">查询</el-button>
      </div>
      <Table
        highlight-row
        ref="currentRowTable"
        :columns="companyColumns"
        :data="shops"
        @on-current-change="companySelect" />
      <Page :current="companyPageIndex" :total="shopTotal" simple style="padding-top: 14px;display: flex;justify-content: center;" @on-change="companyPageChange"/>
    </Modal>
  </div>
</template>

<script>
import {index as companyIndex} from "@/api/activitycompany"
import {store,show,save} from "@/api/activity"
import {index as indexType} from "@/api/activityType"
import { Message } from 'element-ui'
import { getparameter,listparameter } from "@/api/system/dictionary";
import xyTinymce from "@/components/XyTinymce/index.vue";

export default {
  components:{
    xyTinymce
  },
  data() {
    return {
      activeTypeList:[],
      isShow:false,
      type:'add',
      id:'',
      action:`${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
      companykeyword:"",
      parameterList:[],
      form:{
        activeName:"",
        company_ids:[],
        fields:[],
        shopId:0,
        sponsor:0,
        sponsorLogo:"",
        sponsorAdvertise:"",
        recommend:"",
        //slogan:"",
        lecturer:'',
        active_tag:'',
        active_type_id:'',
        template:'',
        date:"",
        applyDate:[],
        address:'',
        relationName:"",
        phoneNumber:"",
        group:"",
        memberSum:"",
        startMemberSum:"",

        greatServices:"",
        // applyDate:[],
        // money:0.00,
        activePlaybill:"",
        illustration:'',
        sort:0,
        content:"",
      },
      rules:{
        activeName:[
          {required:true,message:'请输入活动名称'}
        ],
        // shopId:[
        //   {required:true,message:'请选择发布方'}
        // ],
        active_type_id:[
          {required:true,message:'请选择活动分类'}
        ],
        date:[
          {required:true,message:'请选择活动日期'}
        ],
        applyDate:[
          {required:true,message:'请选择报名日期'}
        ],
        address:[
          {required:true,message:'请输入活动地址'}
        ],
        relationName:[
          {required:true,message:'请输入联系人'}
        ],
        phoneNumber:[
          {required:true,message:'请输入联系电话'},
          {pattern: /^[1][3-9][\d]{9}/,message:'手机号格式错误'}
        ],
        activePlaybill:[
          {required:true,message:'请上传活动海报'}
        ],
        // illustration:[
        //   {required:true,message:'请上传插图'}
        // ],
        content:[
          {required:true,message:'请输入活动内容'}
        ]
      },

      shops:[],
      companyPageIndex:1,
      shopTotal:0,
      isShowShops:false,
      isShowIndex:"",
      companyColumns:[
        {
          title:'名称',
          key:'name'
        }
      ],
      types:[],
      fieldsTable:[
        {
          label: "字段名",
          width: 140,
          customFn: (row) => {
            return ( <el-input placeholder = "必填(如：姓名)"
              type = "text"
              v-model = {
                row.name
              } >
              </el-input>
            );
          },
        },
        {
          label: "字段标识",
          width: 140,
          customFn: (row) => {
            return ( <el-input placeholder = "必填(如：name)"
              type = "text"
              v-model = {
                row.filed
              } >
              </el-input>
            );
          },
        },
        {
          label: "是否必填",
          minWidth: 120,
          customFn: (row,scope) => {
            return (
              <el-select
                placeholder="必填"
                style="width: 100px"
                value={row.is_reqired}

                on={{
                  ["change"]: (e) => (row.is_reqired=e),
                }}
              >
              {
                ['是','否'].map((item,index)=>{
                  return(
                    <el-option
                      // v-for={item in types}
                      value={item}
                      key={index}
                      label={item}
                    >
                    </el-option>
                  )
                })
              }
              </el-select>
            );
          },
        },
        {
          label: "关联数据",
          width: 140,
          customFn: (row) => {
            return (
              <el-select
                placeholder="请选择"
                style="width: 140px"
                value={row.data_name}
                clearable
                on={{
                  ["change"]: (e) => (row.data_name=e.name,row.data_id = e.id),
                }}
              >
              {
                this.parameterList.map((item,index)=>{
                  return(
                    <el-option
                      // v-for={item in types}
                      value={item}
                      key={item.id}
                      label={item.name}
                    >
                    </el-option>
                  )

                })
              }
              </el-select>
            );
          },
        },
      ],
      contentTable: [
        {
          label: "关联方类型",
          width: 140,
          customFn: (row) => {
            return (
              <el-select
                placeholder="请选择关联方类型"
                style="width: 140px"
                value={row.type_name}
                on={{
                  ["change"]: (e) => (row.type_name=e.value,row.type_id = e.id),
                }}
              >
              {
                this.types.map((item,index)=>{
                  return(
                    <el-option
                      // v-for={item in types}
                      value={item}
                      key={item.id}
                      label={item.value}
                    >
                    </el-option>
                  )

                })
              }
              </el-select>
            );
          },
        },
        {
          label: "关联方名称",
          minWidth: 180,
          customFn: (row,scope) => {
            return (
              <el-input
                placeholder="请选择关联方名称"
                type="select"
                readonly
                value={row.name}
                on={{
                  ["focus"]: (e) => (this.isShowShops = true,this.isShowIndex =scope.$index, this.getCompanys()),
                }}
                // value={row.id}
              >
              <i
                class="el-icon-arrow-down el-input__icon"
                slot="suffix"
                on={{
                  ["click"]: (e) => (this.isShowShops = true,this.isShowIndex =scope.$index,this.getCompanys()),
                }}>
              </i>
              </el-input>
            );
          },
        },
      ],
    }
  },
  created(){
    this.getLabels()
    this.getparameterList()
  },
  methods: {

    //上传
    uploadFail(err){
      console.log(err)
    },
    uploadSuccess(response){
      console.log(response)
      this.form.sponsorLogo = response.url
    },
    uploadSuccess1(response){
      console.log(response)
      this.form.activePlaybill = response.url
    },
    uploadSuccess2(response){
      console.log(response)
      this.form.illustration = response.url
    },
    uploadBefore(file){
      console.log(file)
      if((file.size/1000) > 2024){
        Message({
          type:'warning',
          message:'上传图片大小超过2M！'
        })
        return false
      }
    },

    async getparameterList(){
      const res = await listparameter()
      console.log("listparameter",res)
      this.parameterList = res.data
    },
    async getLabels() {
      const res = await getparameter({
        number: "activeCompanyType",
      });
        this.types = res?.detail;
      const res1 = await indexType()
      this.activeTypeList = res1
    },

    async getCompanys(){
      const res = await companyIndex({
        page_size:10,
        page:this.companyPageIndex,
        keyword:this.companykeyword
      })
      this.shops = res.rows
      this.shopTotal = res.total
    },
    companySelect(e){
      // this.form.shopId = {value:e.id,label:e.name}
      this.form.company_ids[this.isShowIndex]['company_id'] = e.id
      this.form.company_ids[this.isShowIndex]['name'] = e.name
    },
    companyPageChange(e){
      this.companyPageIndex = e
      this.getCompanys()
    },

    async getDetail(){
      const res = await show({id:this.id})
      this.form = {
        activeName:res.active_name,
        // shopId:{value:res.shop_id,label:res.shop.name},
        // sponsor:res.sponsor,
        company_ids:res.company_ids?JSON.parse(res.company_ids):[],
        fields:res.fields?JSON.parse(res.fields):[],
        sponsorLogo:res.sponsor_logo,
        sponsorAdvertise:res.sponsor_advertise,
        recommend:res.recommend,
        //slogan:res.slogan,
        lecturer:res?.lecturer,
        active_tag:res?.active_tag,
        active_type_id:res?.active_type_id,
        template:res?.template,
        date:[`${res.start_date}/${res.start_time}`,`${res.end_date}/${res.end_time}`],
        address:res.address,
        relationName:res.relation_name,
        phoneNumber:res.phone_number,
        group:res.group,
        memberSum:res.member_sum,
        startMemberSum:res.start_member_sum,
        greatServices:res.great_services,
        applyDate:[res.apply_start,res.apply_end],
        // money:Number(res.money),
        activePlaybill:res.active_playbill,
        illustration:res.illustration,
        sort:res.sort,
        content:res?.content,
      }

    },

    compareDate(d1, d2) {
      let reg = new RegExp('-', 'g')

      return ((new Date(d1.replace(reg, '/'))) > (new Date(d2.replace(reg, '/'))))

    },
    async updateSortNumber(){
       await this.getDetail()
       this.form.sort = this.sortnumberNew
       await this.submit()

     },
     hasEmptyValue(obj) {
       for (let key in obj) {
         if (obj.hasOwnProperty(key) && key !== 'data_id' && key !== 'data_name') {
           if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
             return true;
           } else if (typeof obj[key] === 'object') {
             if (hasEmptyValue(obj[key]) === true) {
               return true;
             }
           }
         }
       }
       return false;
     },
    submit(){

      let end_date = this.form.date[1]
      let apply_end = this.form.applyDate[1]
      if(this.compareDate(apply_end,end_date)){
        Message({
          type:'warning',
          message:'截止报名日期不能晚于活动结束日期'
        })

        return
      }
      if(this.form.fields&&this.form.fields.length>0){
        this.form.fields.map((item,index)=>{
          if(this.hasEmptyValue(item)){
            Message({
              type:'warning',
              message:`活动提交字段第${index+1}必要字段为空`
            })

            return
          }
        })
      }
      // console.log(this.form)
      // return
      if(this.type === 'add'||this.type === 'copy'){
        console.log(this.form)
        store({
          active_name:this.form.activeName,
          company_ids:this.form.company_ids,
          fields:this.form.fields,
          shop_id:0,
          sponsor:0,
          sponsor_logo:this.form.sponsorLogo,
          sponsor_advertise:this.form.sponsorAdvertise,
          recommend:this.form.recommend,
          //slogan:this.form.slogan,
          lecturer:this.form.lecturer,
          active_tag:this.form.active_tag,
          active_type_id:this.form.active_type_id,
          template:this.form.template,
          start_date:this.form.date[0]?.split('/')[0],
          start_time:this.form.date[0]?.split('/')[1],
          end_date:this.form.date[1]?.split('/')[0],
          end_time:this.form.date[1]?.split('/')[1],
          address:this.form.address,
          relation_name:this.form.relationName,
          phone_number:this.form.phoneNumber,
          group:this.form.group,
          start_member_sum:this.form.startMemberSum,
          member_sum:this.form.memberSum,
          great_services:this.form.greatServices,
          // money:this.form.money,
          apply_start:this.form.applyDate[0],
          apply_end:this.form.applyDate[1],
          active_playbill:this.form.activePlaybill,
          illustration:this.form.illustration,
          sort:this.form.sort,
          content: (() => {
            let content = this.form.content || ''
            // 跟 request.js 保持一致：本地用 VUE_APP_BASE_API，线上用当前域名
            const runtimeBase = window.location.origin.indexOf('localhost') > -1
              ? (process.env.VUE_APP_BASE_API || '')
              : (window.location.origin + '/')
            // 去掉末尾的 /，避免出现 //storage/files
            const apiBase = runtimeBase.replace(/\/$/, '')
            const baseUrl = `${apiBase}/storage/files/`
            // 只处理 img 标签中 src 以 /storage/files 或 ../storage/files 开头、且不是 http(s) 开头的情况
            content = content.replace(
              /(<img[^>]+src=["'])(?:\.\.\/)?\/?storage\/files\/([^"']+)(["'][^>]*>)/g,
              (match, prefix, filePath, suffix) => {
                return `${prefix}${baseUrl}${filePath}${suffix}`
              }
            )
            return content
          })()

        }).then(res => {
          Message({
            type:'success',
            message:'新增活动成功'
          })
          this.isShow = false
          this.$emit('refresh')
        })
        return
      }
      if(this.type === 'editor'){
        save({
          id:this.id,
          active_name:this.form.activeName,
          company_ids:this.form.company_ids,
          fields:this.form.fields,
          shop_id:0,
          sponsor:0,
          sponsor_logo:this.form.sponsorLogo,
          sponsor_advertise:this.form.sponsorAdvertise,
          recommend:this.form.recommend,
          //slogan:this.form.slogan,
          lecturer:this.form.lecturer,
          active_tag:this.form.active_tag,
          active_type_id:this.form.active_type_id,
          template:this.form.template,
          start_date:this.form.date[0]?.split('/')[0],
          start_time:this.form.date[0]?.split('/')[1],
          end_date:this.form.date[1]?.split('/')[0],
          end_time:this.form.date[1]?.split('/')[1],
          address:this.form.address,
          relation_name:this.form.relationName,
          phone_number:this.form.phoneNumber,
          group:this.form.group,
          start_member_sum:this.form.startMemberSum,
          member_sum:this.form.memberSum,
          great_services:this.form.greatServices,
          // money:this.form.money,
          apply_start:this.form.applyDate[0],
          apply_end:this.form.applyDate[1],
          active_playbill:this.form.activePlaybill,
          illustration:this.form.illustration,
          sort:this.form.sort,
          content: (() => {
            let content = this.form.content || ''
            const runtimeBase = window.location.origin.indexOf('localhost') > -1
              ? (process.env.VUE_APP_BASE_API || '')
              : (window.location.origin + '/')
            const apiBase = runtimeBase.replace(/\/$/, '')
            const baseUrl = `${apiBase}/storage/files/`
            content = content.replace(
              /(<img[^>]+src=["'])(?:\.\.\/)?\/?storage\/files\/([^"']+)(["'][^>]*>)/g,
              (match, prefix, filePath, suffix) => {
                return `${prefix}${baseUrl}${filePath}${suffix}`
              }
            )
            return content
          })(),
          // audit_status:1
        }).then(res => {
          Message({
            type:'success',
            message:'编辑活动成功'
          })
          this.isShow = false
          this.$emit('refresh')
        })
      }
    }
  },
  watch:{
    isShow(newVal){
      if(newVal){
        if(this.type === 'editor'||this.type === 'copy'){
          this.getDetail()
        }
      }else{
        this.id = ''
        this.type = ''
        this.$refs['dialog'].reset()
      }
    }
  }

}
</script>

<style scoped lang="scss">
.xy-table-item-label{
  width: 160px;
}
.img__delete{
  transform: scale(0.8,0.8);

  position: absolute;
  top: 4px;
  right: 4px;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
::v-deep .el-upload--picture-card {
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}
::v-deep .avatar-uploader-icon{
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}
::v-deep .avatar {
  width: 80px !important;
  display: block;
  border-radius: 6px;
}

::v-deep .xy-table-item-label{
  width: 160px !important;
}

::v-deep .el-date-editor .el-range-separator{
  width: auto !important;
}

::v-deep .el-input-number .el-input__inner{
  text-align: left !important;
}
  .searchCompanys{
    display: flex;
    justify-content: space-between;
    margin-bottom:16px;
    .el-input{
      width:80%
    }
  }
</style>

