
<template>
  <div class="addActivity app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      v-loading="loading"
      label-width="170px"
      :disabled="mode == 'detail'"
    >
          <el-form-item label="活动名称：" prop="activityName">
            <el-input
              v-model="setQuery.activityName"
              class="item-width-300"
            ></el-input>
          </el-form-item>

          <el-form-item label="活动时间：" prop="activityEndTime">
             <el-date-picker
            v-model="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            class="item-width-350"
            type="datetimerange"
            :default-time="['00:00:00', '23:59:00']"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动类型：">
            <el-radio-group v-model="setQuery.activityType">
                <el-radio :label="1">海报</el-radio>
                <el-radio :label="2">报名</el-radio>
            </el-radio-group>
          </el-form-item>


          <template v-if="setQuery.activityType == 2">
            <el-form-item label="活动地址：" prop="address">
              <el-input
                v-model="setQuery.address"
                class="item-width-300"
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item label="活动报名：">
              <el-checkbox :true-label="1" :false-label="2" v-model="setQuery.activityEnable"></el-checkbox>
            </el-form-item>
            <template v-if="setQuery.activityEnable == 1">
              <el-form-item label="报名次数限制：" prop="limited">
                <el-radio-group v-model="limited">
                    <el-radio :label="1">每人报名次数不限</el-radio>
                    <el-radio :label="2">每人最多报名</el-radio>
                </el-radio-group>
                    <el-input
                    v-if="limited == 2"
                    type="number"
                    v-model.number="setQuery.limited"
                    class="item-width-150 ml10"
                    >
                    <template slot="append">人</template>
                    </el-input>
              </el-form-item>

              <el-form-item label="报名时间：" prop="signupEndTime">
                <el-date-picker
                v-model="date1"
                value-format="yyyy-MM-dd HH:mm:ss"
                class="item-width-350"
                type="datetimerange"
                :default-time="['00:00:00', '23:59:00']"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="付费报名：" prop="price">
                <el-checkbox :true-label="1" :false-label="2" v-model="setQuery.payEnable">开启付费</el-checkbox>
                <el-input
                    v-if="setQuery.payEnable == 1"
                    type="number"
                    v-model="setQuery.price"
                    class="item-width-150 ml10"
                    >
                    <template slot="append">元</template>
                    </el-input>
              </el-form-item>

              <el-form-item v-if="setQuery.payEnable == 1" label="收款方：" prop="authAccount">
                <el-select
                  v-model="setQuery.authAccount"
                  class="item-width-300"
                  placeholder="请选择收款方"
                  :disabled="mode == 'edit'&&status == '进行中'"
                >
                  <el-option
                    v-for="item in authOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="采集信息模板：" prop="dataCollectId">
                <el-select
                  v-model="setQuery.dataCollectId"
                  class="item-width-300"
                  placeholder="请选择采集信息模板"
                  :disabled="mode == 'edit'&&status == '进行中'"
                >
                  <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>

           
          </template>
          <el-form-item  label="活动封面：" prop="activityCover">
            <Upload
              width="100px"
              height="100px"
              id="activityCover"
              type="activityCover"
              :imgUrl="setQuery.activityCover"
              @uploadEnd="uploadEnd"
              :disabled="mode == 'detail'"
            ></Upload>
          </el-form-item>

          <el-form-item v-if="setQuery.activityType == 2" label="活动主图：" prop="activityMain">
            <Upload
              width="100px"
              height="100px"
              type="activityMain"
              id="activityMain"
              :imgUrl="setQuery.activityMain"
              @uploadEnd="uploadEnd"
              :disabled="mode == 'detail'"
            ></Upload>
          </el-form-item>


          <el-form-item label="活动详情：" prop="activityDetail">
            <div style="border: 1px solid #ccc; width: 500px">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                :mode="editorMode"
              />
              <Editor
                style="height: 500px; overflow-y: hidden"
                v-model="setQuery.activityDetail"
                :defaultConfig="editorConfig"
                :mode="editorMode"
                @onCreated="onCreated"
              />
            </div>
          </el-form-item>

    </el-form>

    <div class="btn-group" v-if="mode != 'detail'">
      <el-button>取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save"
        >确 定</el-button
      >
    </div>
  </div>
</template>

<script>
import {activityDetail,activityAddOrUpdate,getDataTemplate,finishComplexList} from '@/api/activity'
import { allFinish } from '@/api/user'
import Upload from "@/components/Upload";
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import OSS from "ali-oss";
import { requestUploadImg, finishUploadImg } from "@/api/common";
export default Vue.extend({
  components: {
    Upload,
    Editor,
    Toolbar,
  },
  data() {
    
    return {
      status:'',
      date:'',
      date1:'',
      editor: null,
      editorMode: "default", // or 'simple'
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            // 自定义上传
            customUpload(file, insertFn) {
              // file 即选中的文件
              requestUploadImg({
                fineName: file.name,
                operate: "OTHER",
              }).then((res) => {
                if (res.state == "Success") {
                  const client = new OSS({
                    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
                    region: res.content.endPoint.split(".")[0],
                    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
                    accessKeyId: res.content.token.accessKeyId,
                    accessKeySecret: res.content.token.accessKeySecret,
                    // 填写Bucket名称。
                    bucket: res.content.bucket,
                    stsToken: res.content.token.securityToken,
                  });

                  client
                    .multipartUpload(res.content.paths[0].join("/"), file)
                    .then((r) => {
                      // 上传完成
                      finishUploadImg([{ path: res.content.paths[0] }]).then(
                        (msg) => {
                          if (msg.state == "Success") {
                            let url =
                              "http://" +
                              res.content.bucket +
                              "." +
                              res.content.endPoint +
                              "/" +
                              res.content.paths[0].join("/");
                            insertFn(url, "", "");
                          }
                        }
                      );
                    })
                    .catch((err) => {
                      console.log(err); //上传失败之后
                    });
                }
              });
            },
          },
        },
      },
      mode: "add",
      loading: false,
      limited:1,
      setQuery: {
        shopId: 0,
        activityType:1,
        "activityCover": "",
        "activityMain":"",
        "activityDetail": "",
        "activityEnable": 1,
        "activityEndTime": "",
        "activityName": "",
        "activityStartTime": "",
        "authAccount": "",
        "dataCollectId": '',
        "limited": 0,
        "payEnable": 1,
        "price": 0,
        "signupEndTime": "",
        "signupStartTime": ""
      },
      
      authOptions:[],
      options: [],
      options1:[],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    rules() {

      if(this.setQuery.activityType == 1){
        return  {
          activityName: [
            { required: true, message: "请输入活动名称", trigger: "blur" },
          ],
          activityEndTime: [
            { required: true, message: "请选择活动时间", trigger: "change" },
          ],
           activityDetail: [
            { required: true, message: "请输入活动详情", trigger: "blur" },
          ],
           activityCover: [
            { required: true, message: "请上传活动封面", trigger: "change" },
          ],
  
        }
      }else{

        return  {
          activityName: [
            { required: true, message: "请输入活动名称", trigger: "blur" },
          ],
          activityEndTime: [
            { required: true, message: "请选择活动时间", trigger: "change" },
          ],
           signupEndTime: [
            { required: true, message: "请选择报名时间", trigger: "change" },
          ],
          address: [
            { required: true, message: "请输入活动地址", trigger: "blur" },
          ],
          //  limited: [
          //   { required: true, message: "请输入报名人数", trigger: "blur" },
          //   { type:'number',min:1, message: "报名人数不能小于1", trigger: "blur" },
  
          // ],
          price:[
            { required: true, message: "请输入报名费用", trigger: "blur" },
             { validator: this.validatePrice, trigger: 'blur' }
          ],
           authAccount: [
            { required: true, message: "请选择收款账户", trigger: "change" },
          ],
           dataCollectId: [
            { required: true, message: "请选择信息模板", trigger: "change" },
          ],
          activityCover: [
            { required: true, message: "请上传活动封面", trigger: "change" },
          ],
          activityMain: [
            { required: true, message: "请上传活动主图", trigger: "change" },
          ],
           activityDetail: [
            { required: true, message: "请输入活动详情", trigger: "blur" },
          ],
  
        }
      }
    }
  },
  watch: {
    date(val){
      if(val){
        this.setQuery.activityStartTime = val[0]
        this.setQuery.activityEndTime = val[1]
      }else{
        this.setQuery.activityStartTime = ''
        this.setQuery.activityEndTime = ''
      }
    },
    date1(val){
      if(val){
        this.setQuery.signupStartTime = val[0]
        this.setQuery.signupEndTime = val[1]
      }else{
        this.setQuery.signupStartTime = ''
        this.setQuery.signupEndTime = ''
      }
    },
    limited(val){
      if(val == 1){
        this.setQuery.limited = 0
        this.rules.limited = [

        ]
      }else{
        this.setQuery.limited = 1
         this.rules.limited = [
          { required: true, message: "请输入报名人数", trigger: "blur" },
          { type:'number',min:1, message: "报名人数不能小于1", trigger: "blur" },

        ]
      }
    },
    'setQuery.payEnable'(val){
      if(val == 1){
        this.rules.price = [
          { required: true, message: "请输入报名费用", trigger: "blur" },
           { validator: this.validatePrice, trigger: 'blur' }
        ]
      }else if(val == 2){
        delete this.rules.price
        this.$nextTick(()=>{
          this.$refs.setQuery.clearValidate('price')
        })
      }
    },
    "setQuery.activityEnable"(val){
      if(val == 2){//不需要报名
        this.setQuery.authAccount = ''
        this.setQuery.dataCollectId = ''
        this.setQuery.payEnable = 1
        this.limited = 1
        this.date1 = ''
      }
   
    }
  },
  methods: {
    validatePrice  (rule, value, callback) {
      if(value<0.01||value>999999){
        callback(new Error('价格只支持0.01~999999'));
      }else{
        callback()
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      if (this.mode == "detail") {
        this.editor.disable();
      }
    },
    uploadEnd(val) {
      console.log(val);
      this.setQuery[val.type] = val.url;
    },

    save() {
      this.$refs.setQuery.validate((v) => {
        if (v) {
          this.loading = true;
          if(this.setQuery.activityType == 1){
            this.setQuery.activityEnable = 2
          }
          activityAddOrUpdate(this.setQuery).then((res) => {
            this.loading = false;
            if (res.state == "Success") {
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
              });
              this.$router.push("/operationManage/activityManage/index");
            }else{
              this.loading = false;
            }
          });
        }else{
          this.$message.error('请检查是否有必填项未填');
        }
      });
    },

    // 详情
    get() {
      this.loading = true;
      let id = this.$route.query.id
      activityDetail({id}).then((res) => {
        this.loading = false;
        if (res.state == "Success") {
          this.setQuery = res.content;
          this.setQuery.id = id
          this.date = [this.setQuery.activityStartTime+':00',this.setQuery.activityEndTime+':00']
          this.date1 = [this.setQuery.signupStartTime+':00',this.setQuery.signupEndTime+':00']
          if(this.setQuery.limited){
            this.limited = 2
          }else{
            this.limited = 1

          }
        }
      });
    },
    // 获取模板
    getDataTemplate(){
      getDataTemplate({shopId:0}).then(res=>{
        if (res.state == "Success") {
          this.options1 = []
          for (const key in res.content) {
            if (Object.hasOwnProperty.call(res.content, key)) {
              this.options1.push({
                label:res.content[key],
                value:Number(key)
              })
            }
          }
        }
      })
    },
     // 获取当前主体下面的已签约银联账号
    finishComplexList(){
      finishComplexList({
        "accesseId": "",
        "epId": '657c35e3cae1326607ea9ed2'
      }).then(res=>{
         if(res.state == 'Success'){
          let list = []
          res.content.map(item=>{
              list.push({
                value:item.accesser_user_id,
                label:item.externalName
              })
          })
          this.authOptions = list
        }
      })
    },
    // 获取所有的已认证银联号
    allFinish() {
      allFinish().then((res) => {
        if (res.state == "Success") {
          this.authOptions = []
          res.content.map(item=>{
            this.authOptions.push({
              label:item.shop_name||item.accesser_user_id,
              value:item.accesser_user_id,
            })
          })
        }
      });
    }
  },
  created() {
    this.getDataTemplate()
    this.allFinish()
    this.mode = this.$route.query.mode || "add";
    this.status = this.$route.query.status
    if (this.$route.query.id) {
        this.get();
    }
  },
})
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>

<style lang="scss" >
@import "@/styles/element-variables";
.addActivity {
  padding-bottom: 40px;
  .item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    .ml20{
      margin-left: 20px !important;
    }
    .mb20{
      margin-bottom: 20px;
    }
    .textarea textarea{
      height: 40px;
    }
    .icon {
      font-size: 18px;
      font-weight: bold;
      margin-left: 10px;
      cursor: pointer;
      margin-top: 10px;
    }
    .box {
    }
  }
  .btn-group {
    display: flex;
    align-items: center;
    justify-content: center;
  }


}
</style>
