<template>
  <el-dialog
    :title="!dataForm.id ? this.$i18n.t('crud.addTitle') : this.$i18n.t('temp.modify')"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="">
    <el-row>
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="110px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="推广人" prop="tgUserName" :rules="{required: true, message: '推广人必填', trigger: 'blur'}">
              <el-input v-model="dataForm.tgUserName" size="small"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="1">
            <el-form-item label="推广店铺" prop="shopId" :rules="{required: true, message: '推广店铺必填', trigger: 'blur'}">
              <el-select v-model="dataForm.shopId" placeholder="推广店铺" style="width: 300px" @change="shopChange"
                         controls-position="right" :clearable="true">
                <el-option v-for="(item,index) in shopList" :key="index" :label="item.shopName" :value="item.shopId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="寄拍/付费" prop="payType" :rules="{required: true, message: '付费类型必填', trigger: 'blur'}">
              <el-select v-model="dataForm.payType" placeholder="请选择" size="small" style="width: 300px">
                <el-option :key="0" label="寄拍" value="寄拍"></el-option>
                <el-option :key="1" label="付费 " value="付费"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="3">
            <el-form-item label="稿费" prop="payAmt">
              <el-input v-model="dataForm.payAmt"size="small" type="number" placeholder="寄拍不填"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="结算状态" prop="payType">
              <el-select v-model="dataForm.settleStatus" placeholder="请选择" size="small">
                <el-option :key="1" label="待结算" value="待结算"></el-option>
                <el-option :key="2" label="已结算 " value="已结算"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col  :span="10">
            <el-form-item label="订单编号" prop="orderNumber" :rules="{required: true, message: '订单号必填', trigger: 'blur'}">
              <el-input v-model="dataForm.orderNumber" size="small" type="textarea" rows="3" placeholder="多个订单号时需要换行，一个订单号占一行"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :span="10" :offset="1">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" size="small" type="textarea" rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="收款码" prop="pic">
            <el-upload
              :disabled="isView"
              ref="upload"
              :multiple="true"
              :action="$http.adornUrl('/admin/file/simpleUpload')"
              list-type="picture-card"
              :headers="{Authorization: $cookie.get('Authorization_vs'),locale:lang}"
              :on-success="onUploadSuccess"
              :file-list="fileList"
              :limit="1"
              :on-remove="handlePicRemove"
              :on-preview="handlePicPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
            <div  @paste="pasteImg($event)">
              <textarea placeholder="点击这里，然后把图片粘贴" style="width: 100%;height: 100px;border: 1px solid #c9c9c9;border-radius: 5px;"></textarea>
            </div>
          </el-form-item>
        </el-row>
        <div v-if="!dataForm.id">
          <h3>博主信息</h3>
          <el-divider></el-divider>
          <el-row v-for="(upItem, index) in dataForm.videoList" v-if="dataForm.videoList.length > 0">
            <el-col :span="6">
              <el-form-item label="博主ID" :prop="'videoList.' + index + '.upId'" :rules="{required: true, message: '博主ID必填', trigger: 'blur'}">
                <el-select
                  v-model="upItem.upId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入博主ID"
                  :remote-method="queryUpById"
                  @change="changeUpById($event, index)"
                  :loading="queryUpLoading">
                  <el-option
                    v-for="(item2, index2) in upList"
                    :key="index2"
                    :label="item2.upId"
                    :value="item2.upId">
                    <span >{{ item2.upId }}|</span>
                    <span >{{ item2.upName }}|</span>
                    <span >{{ item2.publishPlatform }}|</span>
                    <span >{{ item2.tgUserName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="博主昵称" :prop="'videoList.' + index + '.upName'" :rules="{required: true, message: '博主昵称必填', trigger: 'blur'}">
                <el-select
                  v-model="upItem.upName"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入博主昵称"
                  :remote-method="queryUpByName"
                  @change="changeUpByName($event, index)"
                  :loading="queryUpLoading">
                  <el-option
                    v-for="(item3,index3) in upList"
                    :key="index3"
                    :label="item3.upName"
                    :value="item3.upName">
                    <span >{{ item3.upId }}|</span>
                    <span >{{ item3.upName }}|</span>
                    <span >{{ item3.publishPlatform }}|</span>
                    <span >{{ item3.tgUserName }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="视频平台" :prop="'videoList.' + index + '.publishPlatform'" :rules="{required: true, message: '视频平台必填', trigger: 'blur'}">
                <el-select v-model="upItem.publishPlatform" filterable placeholder="请选择">
                  <el-option
                    v-for="(item4,index4) in videoPlatformList"
                    :key="index4"
                    :label="item4.label"
                    :value="item4.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="粉丝数" :prop="'videoList.' + index + '.fansNum'">
                <el-input v-model="upItem.fansNum" size="small" type="number"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button circle @click.prevent="removeUpItem(upItem)" type="danger" icon="el-icon-delete"></el-button>
              <el-button circle @click.prevent="addUpItem()" type="success" icon="el-icon-plus" v-if="index === dataForm.videoList.length - 1"></el-button>
            </el-col>
          </el-row>
          <el-row v-if="dataForm.videoList.length === 0">
            <el-button circle @click.prevent="addUpItem()" type="success" icon="el-icon-plus"></el-button>
          </el-row>
        </div>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button class="default-btn" @click="visible = false">{{$t("crud.filter.cancelBtn")}}</el-button>
      <el-button class="default-btn primary-btn" type="primary" @click="dataFormSubmit()">{{$t("crud.filter.submitBtn")}}</el-button>
    </span>
    <el-dialog :visible.sync="imgDialogVisible" :append-to-body="true">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </el-dialog>
</template>


<script>
  import { uploadFile } from '@/utils/httpRequest.js'
  export default {
    data () {
      return {
        visible: false,
        lang: localStorage.getItem('lang') || 'zh_CN',
        dataForm: {
          id: null,
          tgUserName: null,
          upId: null,
          upName: null,
          orderNumber: null,
          shopId: this.$store.state.user.shopId,
          shopName: null,
          status: null,
          promotionVideoId: null,
          promotionVideo: null,
          createTime: null,
          updateTime: null,
          settleStatus: '待结算',
          remark: null,
          payType: null,
          payAmt: 0,
          videoList:[{upId:null, upName: null, publishPlatform:null, payAmt:null, fansNum:null}],
          settleQrCodeImg: null
        },
        imgDialogVisible: false,
        dialogImageUrl: null,
        shopList: [],
        fileList:[],
        resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
        isView: false,
        videoPage: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        dataRule: {
        },
        upList:[{}],
        videoPlatformList: [
          {value: '抖音', label: '抖音'},
          {value: '小红书', label: '小红书'},
          {value: '视频号', label: '视频号'},
          {value: '快手', label: '快手'},
          {value: 'B站', label: 'B站'},
        ],
        queryUpLoading: false
      }
    },
    mounted () {
      this.getShopList();
      this.getUpList();
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl('/promotion/promotionOrder/info/' + this.dataForm.id),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              this.dataForm = data
              if(this.dataForm.settleQrCodeImg) {
                this.fileList = [];
                this.fileList.push({url: this.resourcesUrl + this.dataForm.settleQrCodeImg, response: {filePath: this.dataForm.settleQrCodeImg}})
              }
            })
          }
        })
      },
      changeUpById(upId, videoIndex){
        let up = this.upList.find(item => item.upId === upId)
        this.dataForm.videoList[videoIndex].upName = up.upName
        this.dataForm.videoList[videoIndex].upId = up.upId
        this.dataForm.videoList[videoIndex].fansNum = up.fansNum
        this.dataForm.videoList[videoIndex].publishPlatform = up.publishPlatform
      },
      changeUpByName(upName, videoIndex){
        let up = this.upList.find(item => item.upName === upName)
        this.dataForm.videoList[videoIndex].upName = up.upName
        this.dataForm.videoList[videoIndex].upId = up.upId
        this.dataForm.videoList[videoIndex].fansNum = up.fansNum
        this.dataForm.videoList[videoIndex].publishPlatform = up.publishPlatform
      },
      getUpList(upId, upName){
        this.$http({
          url: this.$http.adornUrl('/promotion/promotionUp/list'),
          method: 'get',
          params: this.$http.adornParams({upId: upId, upName:upName})
        }).then(({ data }) => {
          this.upList = data;
        })
      },
      onUploadSuccess(response, file, fileList){
        this.fileList = fileList;
      },
      handlePicRemove(file, fileList){
        this.fileList = fileList;
      },
      handlePicPreview(file){
        this.dialogImageUrl = file.url
        let url = file.response.resourcesUrl + file.response.filePath
        this.videoFlag = this.checkMediaType(url)
        this.imgDialogVisible = true
      },
      queryUpById(upId) {
        if (upId !== '') {
          this.queryUpLoading = true
          this.getUpList(upId, null)
          this.queryUpLoading = false
        } else {
          this.upList = [];
        }
      },
      queryUpByName(upName) {
        if (upName !== '') {
          this.queryUpLoading = true
          this.getUpList(null, upName)
          this.queryUpLoading = false
        } else {
          this.upList = [];
        }
      },
      getShopList() {
        this.$http({
          url: this.$http.adornUrl('/platform/shopDetail/getShopList'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({ data }) => {
          if (data) {
            this.shopList = data
          }
        })
      },
      shopChange (index) {
        this.dataForm.shopName = this.shopList[index].shopName
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.fileList.length > 0){
              this.dataForm.settleQrCodeImg = this.fileList[0].response.filePath
            }
            this.dataForm.shopName = this.shopList.find(item => item.shopId === this.dataForm.shopId).shopName
            this.$http({
              url: this.$http.adornUrl('/promotion/promotionOrder'),
              method: this.dataForm.id ? 'put' : 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({data}) => {
              this.$message({
                message: this.$i18n.t('publics.operation'),
                type: 'success',
              })
              this.visible = false
              this.$emit('refreshDataList')
            })
          }
        })
      },
      addUpItem(){
        this.dataForm.videoList.push({upId:null, upName: null, publishPlatform:null, payAmt:null, fansNum:null})
      },
      removeUpItem(upItem, index){
        if(this.dataForm.videoList.length === 1){
          return
        }
        this.dataForm.videoList.splice(index, 1)
      },
      pasteImg(e) {
        const { items } = e.clipboardData; // 获取粘贴板文件对象
        if (items.length) {
          for (const item of items) {
            if (item.type.indexOf('image') !== -1) {
              const file = item.getAsFile(); // 获取图片文件
              if (file) {
                uploadFile(
                  this.$http.adornUrl('/admin/file/simpleUpload'),
                  file
                ).then(({ data }) => {
                  // this.$refs['file'].value = null // 解决上传同一图片不显示bug
                  // { url: this.resourcesUrl + picArray[i], response: {filePath: picArray[i] }
                  let obj = {url: data.resourcesUrl + data.filePath, response: {filePath: data.filePath }}
                  this.fileList.push(obj)
                })
              }
            }
          }
        }
      },
    }
  }
</script>
