<style>
.account-statistics .ant-card-body .count {
  display: inline-block;
  /* height: 32px;
    line-height: 32px; */
}

/* .creative-name .ant-table td {
    white-space: nowrap;
  } */

.else-label .ant-form-item-label label::after {
  content: '';
  position: relative;
  top: -0.5px;
  margin: 0 8px 0 2px;
}
</style>
<template>
  <div class="creative-name">
    <a-row style="margin-top: 15px">
      <a-card title="">
        <!-- :tabList="title" :activeTabKey="titleKey" @tabChange="key => onTabChange(key, 'titleKey')" -->
        <a-tabs v-model="titleKey" type="editable-card" hideAdd @edit="remove" @change="onTabChange">
          <a-tab-pane v-for="pane in title" :tab="pane.tab" :key="pane.key">
            <a-button @click="dianji" style="margin-bottom: 15px" :disabled="ipagination.total == 15"
              >新增创意</a-button
            >
            <a-form layout="inline">
              <a-row class="image-list-heading vm-panel" style="padding: 8px 20px">
                <a-col :md="7" :sm="8" style="display: flex">
                  <a-form-item label="创意id">
                    <a-input placeholder="请输入广告创意id" v-model="creativeIdTwo"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="7" :sm="8" style="display: flex">
                  <a-form-item label="创意名称">
                    <a-input placeholder="请输入广告创意名称" v-model="creativeName"></a-input>
                  </a-form-item>
                </a-col>
                <a-col :md="4" :sm="4" style="display: flex">
                  <a-button type="primary" style="margin: 0 10px" @click="searchLabel">查询</a-button>
                  <a-button type="primary" style="margin: 0 10px" @click="searchRe">重置</a-button>
                </a-col>
              </a-row>
            </a-form>
            <div v-show="selectedRowKeys.length > 0">
              批量操作：
              <a-select style="width: 120px" v-model="allType">
                <a-select-option value="1">启动</a-select-option>
                <a-select-option value="2">暂停</a-select-option>
                <a-select-option value="4">修改监测链接</a-select-option>
                <a-select-option value="3">删除</a-select-option>
              </a-select>
              <a-button @click="editStatus" style="margin: 0 0 15px 15px" type="primary">确认</a-button>
            </div>
            <a-table
              :columns="columns"
              :dataSource="dataList"
              bordered
              :scroll="{ x: true }"
              :customRow="rowClick"
              size="middle"
              :pagination="ipagination"
              :loading="loadingList"
              :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
              <span slot="action" slot-scope="text, record">
                <a-switch v-model="record.showSwich" @change="onChangeSwitch(record)" />
              </span>
              <span slot="actionTwo" slot-scope="text, record">
                <a @click="editOriginality(record)" :disabled="record.creativeMaterialType+''=='4'">编辑</a>
              </span>
              <span slot="status" slot-scope="text">{{ text | status }}</span>
              <span slot="putStatus" slot-scope="text">{{ text | putStatus }}</span>
              <div slot="coverUrl" slot-scope="text,record">
                <img v-if="record.creativeMaterialType+''=='4'"  :src="JSON.parse(record.materialUrl)[0]" alt="" style="width: 100px" />
                <img v-else  :src="text" alt="" style="width: 100px" />
              </div>
              
              <span slot="captions" slot-scope="text">
                <span v-for="(item, index) of JSON.parse(text)" :key="index">{{ item }}</span>
              </span>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-row>
    <a-modal
      v-model="visibleAll"
      title="批量修改第三方监测链接"
      @ok="handleOkAll"
      :confirmLoading="allLoading"
      :width="800"
    >
      <a-form-item
        label="检测链接"
        :labelCol="{ lg: { span: 4 }, sm: { span: 2 } }"
        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
      >
        <a-input v-model="clickTrackUrl" placeholder="请输入第三方检测链接"> </a-input>
      </a-form-item>
    </a-modal>
    <a-modal v-model="visibleFail" title="错误信息" :footer="null">
      <div v-if="visibleData">
        修改条数：{{ visibleData.totalCount }} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;失败条数：{{ visibleData.failCount }}
        <div style="margin-top: 20px">
          <p v-for="(item, index) of visibleData.failInfo" :key="index">
            <span>名称：{{ item.creativeName }}</span
            ><br />
            <span>错误信息：{{ item.message }}</span>
          </p>
        </div>
      </div>
    </a-modal>
    <a-modal v-model="visible" title="修改" @ok="handleOk" :width="800">
      <a-form @submit="handleSubmit" :form="form" style="margin-top: 20px" :hideRequiredMark="true">
        <a-form-item
          label="素材类型"
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
        >
          <a-radio-group buttonStyle="solid" v-decorator="['creativeMaterialType', { initialValue: 1 }]">
            <a-radio-button :value="1">竖版视频</a-radio-button>
            <a-radio-button :value="2">横版视频</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label=" "
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
          class="else-label"
        >
          <a @click="getVideoList('video')">选择视频</a>
          <br />
          <video :src="video.url" controls="controls" style="width: 25%" v-if="video.url"></video>
        </a-form-item>
        <a-form-item
          label=" "
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
          class="else-label"
        >
          <a @click="getVideoList('image')">选择封面</a>
          <br />
          <img :src="image.coverUrl" style="width: 25%" v-if="image.coverUrl" />
        </a-form-item>
        <a-form-item
          label="创意标题"
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
        >
          <a-input
            class="rending"
            v-decorator="['creativeName', { rules: [{ required: true, message: '请输入创意标题' }] }]"
          >
          </a-input>
        </a-form-item>
        <a-form-item
          label="广告语"
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
        >
          <a-textarea
            class="rending"
            placeholder="请输入广告语"
            v-decorator="['description', { rules: [{ required: true, message: '请输入广告语' }] }]"
            :autosize="{ minRows: 2, maxRows: 6 }"
          ></a-textarea>
        </a-form-item>
        <a-form-item
          label="行动号召"
          :labelCol="{ lg: { span: 4 }, sm: { span: 4 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 17 } }"
        >
          <a-select
            v-decorator="['actionBarText', { rules: [{ required: true, message: '行动号召按钮文案' }] }]"
            showSearch
            allowClear
            placeholder="选择行动号召按钮文案"
            optionFilterProp="children"
            :filterOption="filterOption"
          >
            <a-select-option v-for="appModel in appList" :key="appModel.id" :value="appModel.actionBarText">
              {{ appModel.actionBarText }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="检测链接"
          :labelCol="{ lg: { span: 4 }, sm: { span: 2 } }"
          :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
        >
          <a-input
            v-decorator="[
              'clickTrackUrl',
              {
                rules: [{ required: true, message: '请输入第三方检测链接' }],
              },
            ]"
            placeholder="请输入第三方检测链接"
          >
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- <checkMatemal ref="check" @showVideo="showData"></checkMatemal> -->
  </div>
</template>

<script>
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import moment from 'moment'
import countTo from 'vue-count-to'
import { mapGetters } from 'vuex'
import { deleteAction, getAction, postAction } from '@/api/manage'
// import checkMatemal from './editMatemal'
import pick from 'lodash.pick'

// import lifting from './components/lifting'
const columns = [
  {
    title: '开关',
    align: 'center',
    dataIndex: 'action',
    width: 100,
    scopedSlots: {
      customRender: 'action',
    },
  },
  {
    title: '创意名称',
    dataIndex: 'creativeName',
    align: 'center',
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'actionTwo',
    width: 100,
    scopedSlots: {
      customRender: 'actionTwo',
    },
  },
  {
    title: '封面',
    dataIndex: 'coverUrl',
    scopedSlots: {
      customRender: 'coverUrl',
    },
    align: 'center',
  },
  {
    title: '广告创意状态',
    dataIndex: 'status',
    scopedSlots: {
      customRender: 'status',
    },
    align: 'center',
  },
  {
    title: '投放状态',
    dataIndex: 'putStatus',
    scopedSlots: {
      customRender: 'putStatus',
    },
    align: 'center',
  },
  {
    title: '广告语',
    dataIndex: 'description',
    scopedSlots: {
      customRender: 'description',
    },
    align: 'center',
  },
]
const columnsCXH = [
  {
    title: '开关',
    align: 'center',
    dataIndex: 'action',
    width: 100,
    scopedSlots: {
      customRender: 'action',
    },
  },
  {
    title: '创意名称',
    dataIndex: 'packageName',
    align: 'center',
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'actionTwo',
    width: 100,
    scopedSlots: {
      customRender: 'actionTwo',
    },
  },
  // {
  //   title: '封面',
  //   dataIndex: 'coverUrl',
  //   scopedSlots: {
  //     customRender: 'coverUrl'
  //   },
  //   align: 'center'
  // },
  // {
  //   title: '广告创意状态',
  //   dataIndex: 'status',
  //   scopedSlots: {
  //     customRender: 'status'
  //   },
  //   align: 'center'
  // },
  {
    title: '投放状态',
    dataIndex: 'putStatus',
    scopedSlots: {
      customRender: 'putStatus',
    },
    align: 'center',
  },
  {
    title: '广告语',
    dataIndex: 'captions',
    scopedSlots: {
      customRender: 'captions',
    },
    align: 'center',
  },
]
export default {
  name: 'account-statistics',
  components: {
    ACol,
    ARow,
    countTo,
    // checkMatemal,
  },

  data: function () {
    return {
      creativeName: '',
      creativeIdTwo: '',
      visible: false,
      visibleAll: false,
      allLoading: false,
      visibleFail: false,
      visibleData: null,
      clickTrackUrl: '',
      image: {},
      video: {},
      duration: 1000,
      showEdit: false,
      many: 1200,
      manyTwo: null,
      columns: columns,
      dataList: [],
      loadingList: false,
      rowClick: (record, index) => ({
        // 事件
        on: {
          dblclick: () => {
            // 点击改行时要做的事情
            // alert(index)
          },
        },
      }),
      ipagination: {
        current: 1,
        pageSize: 15,
        //   pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        //   showSizeChanger: true,
        total: 0,
        onChange: (current) => {
          // 切换分页时的回调，
          // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
          this.ipagination.current = current
          this.getDataList(this.titleKey)
        },
      },
      name: null,
      title: [],
      titleKey: null,
      selectedRowKeys: [],
      selectedRowKeysValue: [],
      allType: '1',
      form: this.$form.createForm(this),
      appList: [],
      creativeId: '',
    }
  },
  filters: {
    status(sta) {
      var data = {
        '-1': '不限',
        1: '已暂停',
        3: '计划超预算',
        6: '余额不足',
        11: '组审核中',
        12: '组审核未通过',
        14: '已结束',
        15: '组已暂停',
        17: '组超预算',
        19: '未达投放时间',
        41: '审核中',
        42: '审核未通过',
        46: '已暂停',
        52: '投放中',
        53: '作品异常',
        54: '视频审核通过',
      }
      return data[sta]
    },
    putStatus(sta) {
      var data = {
        1: '投放中',
        2: '暂停',
      }
      return data[sta]
    },
  },
  methods: {
    editOriginality(item) {
      this.creativeId = item.creativeId
      if (item.creativeMaterialType + '' == '4') {
        this.image.coverUrl = JSON.parse(item.materialUrl)

        this.visible = true
      } else {
        getAction('/kuaishou/batch/getActionBarText', {
          campaignId: localStorage.getItem('campaignList'),
        }).then((res) => {
          if (res.success) {
            this.appList = res.result
          }
        })
        getAction('/kuaishou/batch/getVideoDetail', {
          photoId: item.photoId,
        }).then((res) => {
          if (res.success) {
            console.log(res)
            this.video.url = res.result.url
            this.video.photoId = res.result.photoId

            this.image.coverUrl = item.coverUrl
            this.image.imageToken = item.imageToken

            this.visible = true
            this.$nextTick(() => {
              this.form.setFieldsValue(
                pick(item, ['clickTrackUrl', 'actionBarText', 'creativeName', 'description', 'creativeMaterialType'])
              )
            })
          }
        })
      }
    },
    handleOk() {
      this.handleSubmit()
    },
    handleOkAll() {
      this.allLoading = true
      var params = {}
      params.accountId = localStorage.getItem('campaignAccountId')
      params.creativeJson = {
        clickTrackUrl: this.clickTrackUrl,
      }
      params.creativeIds = this.selectedRowKeysValue
      postAction('/kuaishou/batch/batchUpdateCreative', params).then((res) => {
        console.log(res)
        if (res.success) {
          if (res.result.failCount > 0) {
            this.allLoading = false
            this.visibleAll = false
            this.visibleFail = true
            this.visibleData = res.result
          } else {
            this.getDataList(localStorage.getItem('originalityKeyElse'))
            this.$message.success('批量修改成功')
            this.allType = '1'
            this.selectedRowKeysValue = []
            this.selectedRowKeys = []
            this.clickTrackUrl = ''
            this.visibleAll = false
          }
        } else {
          this.$message.error('修改失败')
          this.visibleAll = false
        }
      })
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          var params = {
            photoId: this.video.photoId,
            imageToken: this.image.imageToken,
            ...values,
            creativeId: this.creativeId,
            accountId: localStorage.getItem('campaignAccountId'),
          }
          console.log(params)
          postAction('/kuaishou/batch/updateCreative', params).then((res) => {
            console.log(res)
            if (res.result.code == 0) {
              this.visible = false
              this.$message.success('修改成功')
              this.getDataList(localStorage.getItem('originalityKeyElse'))
            } else {
              this.$message.error(res.result.message)
            }
          })
        }
      })
    },
    getVideoList(type) {
      if (type == 'video') {
        this.$refs.check.showCheck(this.getData('creativeMaterialType'), '/kuaishou/batch/getVideoList', type)
      } else {
        this.$refs.check.showCheck(this.getData('creativeMaterialType'), '/kuaishou/batch/getImageList', type)
      }
    },
    showData(item, type) {
      if (type == 'video') {
        this.video = {}
        console.log(item, 'v')
        this.video.url = item.url
        this.video.photoId = item.photoId
      } else {
        console.log(item, 'i')
        this.image = {}
        this.image.coverUrl = item.url
        this.image.imageToken = item.imageToken
      }
    },
    getData(className) {
      return this.form.getFieldValue(className)
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    onChangeSwitch(item) {
      console.log(item)
      var params = {}
      params.accountId = localStorage.getItem('campaignAccountId')
      params.putStatus = item.showSwich ? 1 : 2
      params.userId = this.userInfo().id
      params.creativeIds = [item.creativeId]
      postAction('/kuaishou/batch/batchUpdateCreativeStatus', params).then((res) => {
        console.log(res)
      })
    },
    editStatus() {
      if (this.allType == '4') {
        // /kuaishou/batch/batchUpdateCreative
        this.visibleAll = true
        this.allLoading = false
      } else {
        var params = {}
        params.accountId = localStorage.getItem('campaignAccountId')
        params.putStatus = this.allType
        params.userId = this.userInfo().id
        params.creativeIds = this.selectedRowKeysValue
        postAction('/kuaishou/batch/batchUpdateCreativeStatus', params).then((res) => {
          console.log(res)
          if (res.success) {
            this.getDataList(localStorage.getItem('originalityKeyElse'))
            this.$message.success('批量修改成功')
            this.allType = '1'
            this.selectedRowKeysValue = []
            this.selectedRowKeys = []
          }
        })
      }
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRowKeysValue = selectionRows.map((item) => {
        return item.creativeId
      })
      //    this.selectedRowKeysValue.length > 0 ? this.selectedRowKeysValue :
    },
    onTabChange(key) {
      this.ipagination.current = 1
      this.titleKey = key
      localStorage.setItem('originalityKeyElse', key)
      this.getDataList(key)
    },
    show() {
      if (!this.showEdit) {
        this.many = this.manyTwo
      } else {
        this.manyTwo = this.many
      }
    },
    editShow(item) {
      if (!item.edit) {
        item.money = item.elseMoney
      } else {
        item.elseMoney = item.money
      }
    },
    dianji() {
      if (localStorage.getItem('step')) {
        this.$message.error('请关闭创建页面后,重新进行创建')
        return
      } else {
        localStorage.setItem('step', 2)
        var dataJson = JSON.stringify(this.title)
        console.log(this.title, this.titleKey)
        localStorage.setItem('pans', dataJson)
        localStorage.setItem('pansKey', this.titleKey)
        this.$router.replace({
          path: '/account/stepForm',
        })
      }
    },
    searchLabel() {
      this.ipagination.current = 1
      // this.getDataList(localStorage.getItem('originalityKey'))
      if (
        this.title.filter((item) => {
          return item.key == this.titleKey + ''
        })[0].unitType == 7
      ) {
        this.columns = columnsCXH
        this.getCXHList(localStorage.getItem('originalityKeyElse'))
      } else {
        this.columns = columns
        this.getDataList(localStorage.getItem('originalityKeyElse'))
      }
    },
    searchRe() {
      this.creativeIdTwo = ''
      this.creativeName = ''
      if (
        this.title.filter((item) => {
          return item.key == this.titleKey + ''
        })[0].unitType == 7
      ) {
        this.columns = columnsCXH
        this.getCXHList(localStorage.getItem('originalityKeyElse'))
      } else {
        this.columns = columns
        this.getDataList(localStorage.getItem('originalityKeyElse'))
      }
    },
    getDataList(id) {
      this.loadingList = true
      this.dataList = []
      var params = {}
      params.unitId = id
      params.accountId = localStorage.getItem('campaignAccountId')
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize
      params.creativeId = this.creativeIdTwo
      params.creativeName = this.creativeName
      getAction('/kuaishou/batch/getCreativeList', params).then((res) => {
        if (res.code == 0) {
          this.loadingList = false
          this.dataList = res.result.records.map((v, index) => {
            return {
              ...v,
              key: index,
              edit: false,
              showSwich: v.putStatus == 1 ? true : false,
            }
          })
          this.ipagination.total = res.result.total
        } else {
          this.$message.error(res.message)
          this.loadingList = false
        }
      })
    },

    getCXHList(id) {
      this.loadingList = true
      this.dataList = []
      var params = {}
      params.unitId = id
      params.accountId = localStorage.getItem('campaignAccountId')
      params.pageNo = this.ipagination.current
      params.pageSize = this.ipagination.pageSize
      // params.creativeId = this.creativeIdTwo
      // params.creativeName = this.creativeName
      getAction('/ctop/kuaishouProgramCreative/list', params).then((res) => {
        console.log(res)
        if (res.code == 0) {
          this.loadingList = false
          this.dataList = res.result.records.map((v, index) => {
            return {
              ...v,
              key: index,
              edit: false,
              showSwich: v.putStatus == 1 ? true : false,
            }
          })
          this.ipagination.total = res.result.total
        } else {
          this.$message.error(res.message)
          this.loadingList = false
        }
      })
    },
    remove(targetKey) {
      let activeKey = this.titleKey
      let lastIndex
      this.title.forEach((pane, i) => {
        if (pane.key === targetKey) {
          lastIndex = i - 1
        }
      })
      const panes = this.title.filter((pane) => pane.key !== targetKey)
      if (panes.length && activeKey === targetKey) {
        if (lastIndex >= 0) {
          activeKey = panes[lastIndex].key
        } else {
          activeKey = panes[0].key
        }
      }
      this.title = panes
      this.titleKey = activeKey
      if (this.title.length == 0) {
        this.$bus.$emit('remove', '/batchCreation/creativeList')
      } else {
        localStorage.setItem('originalityElse', JSON.stringify(this.title))
        localStorage.setItem('originalityKeyElse', this.titleKey)
        this.getDataList(activeKey)
      }
    },
  },
  watch: {},
  computed: {},
  activated() {
    this.titleKey = localStorage.getItem('originalityKeyElse')
    this.creativeIdTwo = ''
    this.creativeName = ''
    console.log(this.$route.params)
    this.title = JSON.parse(localStorage.getItem('originalityElse')).map((item) => {
      return {
        key: item.unitId ? item.unitId + '' : item.key + '',
        tab: item.unitName ? '广告组：' + item.unitName : '广告组：' + item.tab,
        sceneId: item.sceneId,
        bid_type: item.ocpxActionType,
        unitType: item.unitType,
      }
    })
    if (
      this.title.filter((item) => {
        return item.key == this.titleKey + ''
      })[0].unitType == 7
    ) {
      this.columns = columnsCXH
      this.getCXHList(localStorage.getItem('originalityKeyElse'))
    } else {
      this.columns = columns
      this.getDataList(localStorage.getItem('originalityKeyElse'))
    }

    this.data = JSON.parse(localStorage.getItem('originalityElse'))
  },
}
</script>