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

  .account-index .ant-table td {
    white-space: nowrap;
  }
</style>
<template>
  <div class="account-index">
    <a-row class="image-list-heading vm-panel">
      <a-col :span="24" style="display:flex">
        <Treeselect :appId.sync="appId" :multiple="false" request="2,4" ref="treeSelect" style="margin:8px 20px" />
        <a-button type="primary" style="margin:10px" @click="addUser">搜索</a-button>
      </a-col>
    </a-row>
    <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="campaignIdSearch"></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="campaignName"></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="4" :sm="8" 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>
    <a-row :gutter="15" style="margin-top:15px">
      <a-col :span="12">
        <a-card hoverable title="总花费">
          <countTo :startVal="0" :endVal="cost" :duration="duration" :decimals="2" class="count"></countTo>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card hoverable title="余额">
          <countTo :startVal="0" :endVal="balance" :duration="duration" :decimals="2" class="count"></countTo>
        </a-card>
      </a-col>
    </a-row>
    <a-row style="margin-top:15px">
      <a-card>
        <a-button @click="dianji" style="margin-bottom:15px;">新增广告计划</a-button>
        <div v-show="selectedRowKeys.length > 0">
          请输入修改金额：
          <a-select style="width: 120px" v-model="allPrice">
            <a-select-option value="1">比例</a-select-option>
            <a-select-option value="2">出价</a-select-option>
          </a-select>
          <a-input-number :min="-1" :step="0.1" v-model="allMoneyProportion" style="width:150px" @fouse.stop
            v-if="allPrice == '1'" />
          <a-input-number :min="0" :step="0.01" v-model="allMoney" style="width:150px" @fouse.stop v-else />

          <!-- <a-input-number :min="0" :step="0.01" v-model="allMoney" style="width:150px" @fouse.stop /> -->
          <a-button @click="editMoney" style="margin:0 15px 15px 15px" type="primary">修改</a-button>

          批量操作：
          <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="3">删除</a-select-option>
          </a-select>
          <a-button @click="editStatus" style="margin:0 0 15px 15px" type="primary">确认</a-button>
        </div>
        <a-modal v-model="visible" title="错误信息" onOk="handleOk" :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.campaignName?item.campaignName:item.unitName }}</span><br />
                <span>错误信息：{{ item.message }}</span>
              </p>
            </div>
          </div>
        </a-modal>
        <a-table size="middle" :loading="loadingList" :columns="columns" :dataSource="dataList" bordered
          :scroll="{ x: 2000 }" :customRow="rowClick" :pagination="ipagination"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
          <template slot="campaignName" slot-scope="text, record">
            <div style="display:flex;justify-content: center;">
              <a @click="toDetail(record)" class="count" v-show="!record.editName">{{ text }}</a>
              <a-input v-show="record.editName" v-model="record.campaignName" style="width:150px" @fouse.stop />
              <a-icon :type="record.editName ? 'check' : 'edit'"
                @click.stop=";(record.editName = !record.editName), editShowName(record)" style="margin-left:10px"
                class="count" />
            </div>
          </template>
          <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-popconfirm @confirm="getInfo(record)">
              <div slot="title">
                <div>
                  计划名称:
                  <a-input placeholder="请输入" v-model="refuseReason" style="display: inline-block;width: 500px;" />
                </div>
              </div>
              <!-- <a-button slot="okText" type="primary" :disabled="refuseReason == ''">确定</a-button> -->
              <a @click="setData(record)">复制</a>
            </a-popconfirm>
          </span>
          <span slot="campaignType" slot-scope="text">
            {{ text | typeStatus }}
          </span>
          <span slot="status" slot-scope="text">
            {{ text | status }}
          </span>
          <span slot="putStatus" slot-scope="text">
            {{ text | putStatus }}
          </span>
          <span slot="createChannel" slot-scope="text">
            {{ text | createChannel }}
          </span>

          <template slot="dayBudget" slot-scope="text, record">
            <div style="display:flex;justify-content: center;">
              <span v-show="!record.edit" class="count">{{ text ? (text / 1000).toFixed(2) : '不限制预算' }}</span>
              <a-input-number :min="0" :step="0.01" v-show="record.edit" v-model="record.elseMoney" style="width:150px"
                @fouse.stop />
              <a-icon :type="record.edit ? 'check' : 'edit'"
                @click.stop=";(record.edit = !record.edit), editShow(record)" style="margin-left:10px" class="count" />
            </div>
          </template>
        </a-table>
      </a-card>
    </a-row>
    <a-modal v-model="jihua" title="广告组选择" @afterClose="clear" :width="900" :maskClosable="false">
      <a-form-item label="广告组名称" :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
        :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }">
        <a-select v-model="unitId" style="width: 100%" optionFilterProp="children" showSearch
          :filterOption="filterOption" @change="getUnitData($event)">
          <a-select-option v-for="item in groupList" :key="item.unitId" :value="item.unitId">{{
            item.unitName
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <copyGroup ref="copyGroup" v-show="unitId != ''" @failInfo="failInfoShow" :loadingGroup.sync="loadingGroup"
        :jihua.sync="jihua" />
      <template slot="footer">
        <a-button key="submit" type="primary" @click="handleSubmit" :loading="loadingGroup">
          确定
        </a-button>
      </template>
    </a-modal>
  </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 Treeselect from '@/views/modules/Statistics/components/Treeselect.vue'

  import copyGroup from './copyGroup'

  var columns = [{
      title: '开关',
      align: 'center',
      dataIndex: 'action',
      fixed: 'left',
      width: 100,
      scopedSlots: {
        customRender: 'action'
      }
    },
    {
      title: '广告计划名称',
      align: 'center',
      dataIndex: 'campaignName',
      fixed: 'left',
      width: 300,
      scopedSlots: {
        customRender: 'campaignName'
      }
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'actionTwo',
      fixed: 'left',
      width: 100,
      scopedSlots: {
        customRender: 'actionTwo'
      }
    },
    {
      title: '计划单日预算金额',
      align: 'center',
      dataIndex: 'dayBudget',
      scopedSlots: {
        customRender: 'dayBudget'
      },
      width: 200
    },
    {
      title: '计划状态',
      align: 'center',
      dataIndex: 'status',
      scopedSlots: {
        customRender: 'status'
      }
    },
    {
      title: '计划类型',
      align: 'center',
      dataIndex: 'campaignType',
      scopedSlots: {
        customRender: 'campaignType'
      }
    },

    {
      title: '渠道',
      align: 'center',
      dataIndex: 'createChannel',
      filters: [{
          text: '投放后台创建',
          value: '0'
        },
        {
          text: '汇创助手创建',
          value: '1'
        }
      ],
      onFilter: (value, record) =>
        record.createChannel
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
      scopedSlots: {
        customRender: 'createChannel'
      }
    },
    {
      title: '投放状态',
      align: 'center',
      dataIndex: 'putStatus',
      scopedSlots: {
        customRender: 'putStatus'
      }
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'putCreateTime'
    },
    {
      title: '更新时间',
      align: 'center',
      dataIndex: 'putUpdateTime'
    }
  ]
  export default {
    name: 'account-statistics',
    components: {
      ACol,
      ARow,
      countTo,
      Treeselect,
      copyGroup
    },
    data: function () {
      return {
        campaignIdSearch: '',
        campaignName: '',
        loadingList: false,
        form: this.$form.createForm(this),
        jihua: false,
        refuseReason: '',
        visibleEdit: false,
        loadingGroup: false,
        allType: '1',
        duration: 1000,
        showEdit: false,
        many: 0,
        manyTwo: 0,
        cost: 0,
        balance: 0,
        columns,
        dataList: [],
        groupList: [],
        appId: '',
        planId: '',
        selectedRowKeys: [],
        selectedRowKeysValue: [],
        allMoney: null,
        allPrice: '1',
        allMoneyProportion: 1.2,
        visible: false,
        visibleData: null,
        rowClick: (record, index) => ({
          // 事件
          on: {
            dblclick: () => {}
          }
        }),
        ipagination: {
          current: 1,
          pageSize: 10,
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          onChange: current => {
            // 切换分页时的回调，
            // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
            this.ipagination.current = current
            if (this.campaignId == '' && this.campaignName == '') {
              this.addUser()
            } else {
              var params = {}
              params.accountId = this.appId + ''
              params.pageNo = current
              params.pageSize = this.ipagination.pageSize
              params.campaignId = this.campaignId
              params.campaignName = this.campaignName
              this.getCampaignList(params)
            }

          },
          total: 0
        },
        url: {},
        type: '',
        campaignName: '',
        campaignBudget: 'UNLIMITED',
        unitId: '',
        campaignId: ''
      }
    },
    filters: {
      typeStatus(type) {
        // 2 - 提升应用安装;
        // 3 - 获取电商下单;
        // 4 - 推广品牌活动;
        // 5 - 收集销售线索;
        var data = ['', '', '提升应用安装', '获取电商下单', '推广品牌活动', '收集销售线索']
        return data[type]
      },
      status(sta) {
        var data = {
          '-1': '不限',
          1: '已暂停',
          3: '计划超预算',
          4: '有效',
          6: '余额不足'
        }
        return data[sta]
      },
      putStatus(sta) {
        var data = {
          1: '投放中',
          2: '暂停'
        }
        return data[sta]
      },
      createChannel(sta) {
        var data = {
          0: '投放后台',
          1: '汇创助手'
        }
        return data[sta]
      }
    },
    methods: {
      failInfoShow(item) {
        if (item) {
          this.visible = true
          this.visibleData = item
        } else {
          this.$message.success('创建成功')
          this.addUser()
        }
      },
      handleOkEdit(e) {},
      clear() {
        this.unitId = ''
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      getUnitData(e) {
        console.log(this.unitId)
        var params = {
          accountId: this.appId,
          unitId: this.unitId,
          campaignId: this.campaignId,
          planId: this.planId
        }
        localStorage.setItem('advertisingGroupKey', this.campaignId)
        this.$refs.copyGroup.handleOk(params)
        //   handleSubmit
      },
      handleSubmit(e) {

        this.$refs.copyGroup.handleSubmit(e)
      },
      toDetail(record) {

        localStorage.setItem('advertisingGroupKey', record.campaignId)
        localStorage.setItem('accountId', this.appId)

        getAction('/kuaishou/batch/getAsyncCreativeList', {
          campaignId: record.campaignId,
          accountId: this.appId
        }).then(() => {
          localStorage.setItem('campaignId', record.campaignId)
          if (localStorage.getItem('advertisingGroup')) {
            var dataElse = JSON.parse(localStorage.getItem('advertisingGroup'))
            console.log(dataElse)
            for (let i = 0; i < dataElse.length; i++) {
              if (dataElse[i].key == record.key) {
                this.$router.replace({
                  path: '/account/advertisingGroup'
                })
                return
              }
            }
            dataElse.push(record)
            localStorage.setItem('advertisingGroup', JSON.stringify(dataElse))
          } else {
            var data = [record]
            localStorage.setItem('advertisingGroup', JSON.stringify(data))
          }
          this.$router.replace({
            path: '/account/advertisingGroup'
          })
        })

      },
      setData(item) {
        let date = new Date()
        let y = date.getFullYear()
        let MM = date.getMonth() + 1
        MM = MM < 10 ? '0' + MM : MM
        let d = date.getDate()
        d = d < 10 ? '0' + d : d
        this.refuseReason = item.campaignName + '-' + y + '/' + MM + '/' + d
      },
      getInfo(item) {
        if (this.refuseReason == '') {
          this.$message.error('请输入计划名称')
          return
        } else {
          let params = {}
          params.type = item.campaignType
          //   params.campaignBudget = this.campaignBudget
          params.dayBudget = item.dayBudget
          params.campaignName = this.refuseReason
          params.accountId = this.appId + ''
          postAction('/kuaishou/batch/campaignCreate', params).then(res => {
            if (res.success) {
              this.jihua = true
              this.loadingGroup = false
              this.refuseReason = ''
              this.unitId = ''
              // 7156834
              this.planId = res.result
              this.campaignId = item.campaignId
              this.getDataList(item.campaignId)
              this.addUser()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      },
      onChangeSwitch(item) {
        console.log(item)
        var params = {}
        params.accountId = this.appId + ''
        params.putStatus = item.showSwich ? 1 : 2
        params.userId = this.userInfo().id
        params.campaignIds = [item.campaignId]
        postAction('/kuaishou/batch/batchUpdateStatus', params).then(res => {})
      },
      ...mapGetters(['nickname', 'avatar', 'userInfo']),
      searchLabel() {
        // this.ipagination.current = 1
        if (this.appId) {
          var params = {}
          params.accountId = this.appId + ''
          params.pageNo = this.ipagination.current
          params.pageSize = this.ipagination.pageSize
          params.campaignId = this.campaignIdSearch
          params.campaignName = this.campaignName
          this.getCampaignList(params)
        } else {
          this.$message.error('请选择账户')
        }
      },
      searchRe() {
        this.campaignIdSearch = ''
        this.campaignName = ''
        this.searchLabel()
      },
      addUser() {
        this.loading = true
        this.dataList = []
        var params = {}
        params.accountId = this.appId + ''
        params.pageNo = this.ipagination.current
        params.pageSize = this.ipagination.pageSize
        if (this.appId) {
          this.getSpend(params)
          this.getCampaignList(params)
        } else {
          this.$message.error('请选择账户')
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRowKeysValue = selectionRows.map(item => {
          return item.campaignId
        })
        //    this.selectedRowKeysValue.length > 0 ? this.selectedRowKeysValue :
      },
      editStatus() {
        var params = {}
        params.accountId = this.appId + ''
        params.putStatus = this.allType
        params.userId = this.userInfo().id
        params.campaignIds = this.selectedRowKeysValue
        postAction('/kuaishou/batch/batchUpdateStatus', params).then(res => {
          console.log(res)
          if (res.success) {
            this.addUser()
            this.selectedRowKeysValue = []
            this.selectedRowKeys = []
          }
        })
      },
      editMoney() {
        if (this.allPrice == '1') {
          var params = {}
          params.accountId = this.appId + ''
          params.proportion = this.allMoneyProportion
          params.userId = this.userInfo().id
          params.campaignIds = this.selectedRowKeysValue
          postAction('/kuaishou/batch/batchUpdateDayBudgetByProportion', params).then(res => {
            console.log(res)
            if (res.success) {
              if (res.result.failCount > 0) {
                this.visible = true
                this.visibleData = res.result
                this.addUser()
              } else {
                this.addUser()
                this.selectedRowKeysValue = []
                this.selectedRowKeys = []
              }
            } else {
              this.$message.error(res.message)
            }
          })
        } else if (this.allPrice == '2') {
          var params = {}
          params.accountId = this.appId + ''
          params.dayBudget = this.allMoney * 1000
          params.userId = this.userInfo().id
          params.campaignIds = this.selectedRowKeysValue
          postAction('/kuaishou/batch/batchUpdateDayBudget', params).then(res => {
            console.log(res)
            if (res.success) {
              if (res.result.failCount > 0) {
                this.visible = true
                this.visibleData = res.result
                this.addUser()
              } else {
                this.addUser()
                this.selectedRowKeysValue = []
                this.selectedRowKeys = []
              }
            } else {
              this.$message.error(res.message)
            }
          })
        }
      },
      getCampaignList(params) {
        this.loadingList = true
        getAction('/kuaishou/batch/getCampaignList', params).then(res => {
          if (res.code == 0) {
            this.loadingList = false
            this.dataList = res.result.records.map((v, index) => {
              return {
                ...v,
                key: index,
                edit: false,
                editName: false,
                showSwich: v.putStatus == 1 ? true : false
              }
            })
            this.ipagination.total = res.result.total
          } else {
            this.loadingList = false
            this.$message.error(res.message)
          }
        })
      },
      getSpend(item) {
        getAction('/kuaishou/batch/spend', {
          accountId: item.accountId
        }).then(res => {
          if (res.success) {
            console.log(res)
            this.many = res.result.budget
            this.manyTwo = res.result.budget
            this.cost = res.result.cost
            this.balance = res.result.balance
          } else {
            this.$message.error(res.message)
          }
        })
      },
      show() {
        if (!this.showEdit) {
          this.many = this.manyTwo
        } else {
          this.manyTwo = this.many
        }
      },
      editShow(item) {
        if (!item.edit) {
          if (item.elseMoney < 500 || item.elseMoney > 100000000) {
            this.$message.error('请输入大于500并且小于100000000的预算')
            return
          } else {
            item.dayBudget = item.elseMoney * 1000
            var params = {}
            params.accountId = this.appId + ''
            params.dayBudget = item.elseMoney * 1000
            params.userId = this.userInfo().id
            params.campaignIds = [item.campaignId]
            postAction('/kuaishou/batch/batchUpdateDayBudget', params).then(res => {
              console.log(res)
              if (res.result.failCount > 0) {
                this.$message.error(
                  '广告计划：' +
                  res.result.failInfo[0].campaignName +
                  '          ' +
                  '错误：' +
                  res.result.failInfo[0].message
                )
              }
            })
          }
        } else {
          item.elseMoney = item.dayBudget / 1000
        }
        console.log(item)
      },
      editShowName(item) {
        if (!item.editName) {
          var params = {}
          params.accountId = this.appId + ''
          params.campaignId = item.campaignId
          params.campaignName = item.campaignName
          postAction('/kuaishou/batch/updateCampaign', params).then(res => {
            if (res.result.code == 0) {
              this.$message.success('修改成功')
              this.addUser()
            } else {
              this.$message.error(res.result.message)
              this.addUser()
            }
          })
        }
      },
      dianji() {
        if (this.appId == '') {
          this.$message.error('尚未选择需要创建的账户')
        } else {
          localStorage.setItem('accountId', this.appId)
          if (localStorage.getItem('step')) {
            this.$message.error('正在进行广告组创建,请关闭创建页面后,重新进行创建')
            return
          } else {
            localStorage.setItem('step', 0)
            this.$router.replace({
              path: '/account/stepForm'
            })
          }
        }
      },
      getDataList(id) {
        this.groupList = []
        var params = {}
        params.campaignId = id
        params.accountId = this.appId
        params.pageNo = 1
        params.pageSize = 1000
        getAction('/kuaishou/batch/getUnitList', params).then(res => {
          if (res.success) {
            this.groupList = res.result.records
          }
        })
      }
    },
    watch: {},

    computed: {},
    activated() {
      this.manyTwo = this.many
      this.$refs.treeSelect.getParticipateList()
      if (this.appId == '') {
        return
      } else {
        this.searchLabel()
      }
    }
  }
</script>