<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: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:slogan>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            宣传标语：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.slogan" placeholder="请输入宣传标语" clearable style="width: 300px;"></el-input>
          </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: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 { Message } from 'element-ui'
import { getparameter } from "@/api/system/dictionary";
import xyTinymce from "@/components/XyTinymce/index.vue";
    import {replaceAll} from "@/utils/index"

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

        greatServices:"",
        // applyDate:[],
        // money:0.00,
        activePlaybill:"",
        sort:0,
        content:"",
      },
      rules:{
        activeName:[
          {required:true,message:'请输入活动名称'}
        ],
        // shopId:[
        //   {required:true,message:'请选择发布方'}
        // ],
        // sponsor:[
        //   {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:'请上传活动海报'}
        ],
        content:[
          {required:true,message:'请输入活动内容'}
        ]
      },

      shops:[],
      companyPageIndex:1,
      shopTotal:0,
      isShowShops:false,
      isShowIndex:"",
      companyColumns:[
        {
          title:'名称',
          key:'name'
        }
      ],
      types:[],
      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()
  },
  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
    },
    uploadBefore(file){
      console.log(file)
      if((file.size/1000) > 2024){
        Message({
          type:'warning',
          message:'上传图片大小超过2M！'
        })
        return false
      }
    },


    async getLabels() {
      const res = await getparameter({
        number: "activeCompanyType",
      });
        this.types = res?.detail;
    },

    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):[],
        sponsorLogo:res.sponsor_logo,
        sponsorAdvertise:res.sponsor_advertise,
        recommend:res.recommend,
        //slogan:res.slogan,
        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,
        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, '/'))))

    },
    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.type === 'add'||this.type === 'copy'){
        console.log(this.form)
        // return
        store({
          active_name:this.form.activeName,
          company_ids:this.form.company_ids,
          shop_id:0,
          sponsor:0,
          sponsor_logo:this.form.sponsorLogo,
          sponsor_advertise:this.form.sponsorAdvertise,
          recommend:this.form.recommend,
          //slogan:this.form.slogan,
          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,
          sort:this.form.sort,
          content: replaceAll(this.form.content,'../storage/files',`${process.env.VUE_APP_BASE_API}storage/files`)

        }).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,
          shop_id:0,
          sponsor:0,
          sponsor_logo:this.form.sponsorLogo,
          sponsor_advertise:this.form.sponsorAdvertise,
          recommend:this.form.recommend,
          //slogan:this.form.slogan,
          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,
          sort:this.form.sort,
		  content: replaceAll(this.form.content,'../storage/files',`${process.env.VUE_APP_BASE_API}storage/files`),
          // 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>
