<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-item label="广告主开户主体名称">
              <!-- <a-input placeholder="请输入广告主开户主体名称" v-model="queryParam.name"></a-input> -->
              <a-select
                labelInValue
                v-model="allIdUser"
                placeholder="请选择广告主开户主体名称"
                @keyup.enter.native="searchQueryOne"
                @focus="getList"
                showSearch
                optionFilterProp="children"
                :filterOption="filterOption"
                @search="getList"
              >
                <a-select-option :value="item.id" v-for="(item, index) of list" :key="index">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQueryOne" icon="search">查询</a-button>
              <a-button type="primary" @click="searchRe" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <!-- <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
    </div>-->
    <a-tabs @change="callbackTwo" v-model="active">
      <a-tab-pane key="advertiser" tab="广告主列表"></a-tab-pane>
      <a-tab-pane key="product" tab="产品列表">
        <a-tag
          color="blue"
          style="height: 30px; line-height: 30px; font-size: 14px; margin-bottom: 20px"
          v-if="queryParam.advertiserId"
        >
          {{ advertiserName }}
          <a-icon type="close" @click="clear('advertiserId')" />
        </a-tag>
        <a-row :gutter="24" style="margin-bottom: 20px">
          <a-col :md="8" :sm="8">
            <a-input placeholder="请输入产品名称" v-model="queryParam.productName"></a-input>
          </a-col>
          <a-col :md="8" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQueryOne" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="project" tab="项目列表">
        <a-tag
          color="blue"
          style="height: 30px; line-height: 30px; font-size: 14px; margin-bottom: 20px"
          v-if="queryParam.productId"
        >
          {{ advertiserName ? advertiserName + ' / ' + productName : productName }}
          <a-icon type="close" @click="clear('productId')" />
        </a-tag>
        <a-row :gutter="24" style="margin-bottom: 20px">
          <a-col :md="8" :sm="8">
            <a-input placeholder="请输入项目名称" v-model="queryParam.projectName"></a-input>
          </a-col>
          <a-col :md="8" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQueryOne" icon="search">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-button type="primary" slot="tabBarExtraContent" @click="addNew">新增</a-button>
    </a-tabs>

    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="ocpxActionType" slot-scope="text">
          <div v-if="text">
            <span v-for="(item, index) of JSON.parse(text)" :key="index"
              >{{ item | ocpxActionType }}{{ index == JSON.parse(text).length - 1 ? '' : ',' }}</span
            >
          </div>
          <div v-else>-</div>

          <!-- {{ text | ocpxActionType }} -->
        </span>
        <span slot="bidType" slot-scope="text">
          <div v-if="text && JSON.parse(text).length > 0">
            <span v-for="(item, index) of JSON.parse(text)" :key="index"
              >{{ item | bidType }}{{ index == JSON.parse(text).length - 1 ? '' : ',' }}</span
            >
          </div>
          <div v-else>-</div>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
        <span slot="actionProduct" slot-scope="text, record">
          <a @click="handleEditElse(record, 'product')">编辑</a>

          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
        <span slot="actionProject" slot-scope="text, record">
          <a @click="handleEditElse(record, 'project')">编辑</a>

          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </span>
        <span slot="maxBid" slot-scope="text">{{ text / 1000 }}</span>
        <span slot="maxDeepCpaBid" slot-scope="text">{{ text / 1000 }}</span>
        <a slot="name" slot-scope="text, record" @click="toProduct(record, 'product')">{{ text }}</a>
        <a slot="productName" slot-scope="text, record" @click="toProduct(record, 'project')">{{ text }}</a>
      </a-table>
    </div>
    <!-- table区域-begin -->

    <!-- table区域-end -->

    <!-- 表单区域 -->
    <j-select-user ref="userForm" @ok="modalFormOk"></j-select-user>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JTreeSelect from '@/components/jeecg/JTreeSelect'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
import JSelectUser from '@/components/jeecgbiz/JSelectUser'
import { postAction, getAction } from '@/api/manage'
import { mapActions, mapGetters } from 'vuex'

const advertiserColumns = [
  {
    title: '广告主开户主体名称',
    align: 'center',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '联系人姓名',
    align: 'center',
    dataIndex: 'contact',
  },
  {
    title: '联系人手机',
    align: 'center',
    dataIndex: 'mobile',
  },
  {
    title: '联系人邮箱',
    align: 'center',
    dataIndex: 'email',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
const productColumns = [
  {
    title: '产品名',
    align: 'center',
    dataIndex: 'productName',
    scopedSlots: { customRender: 'productName' },
  },
  {
    title: '广告主名称',
    align: 'center',
    dataIndex: 'advertiserId_dictText',
  },
  {
    title: '创建人',
    align: 'center',
    dataIndex: 'userId_dictText',
  },
  {
    title: '行业',
    align: 'center',
    dataIndex: 'industryId_dictText',
  },
  {
    title: '状态',
    align: 'center',
    dataIndex: 'productStatus',
    customRender: function (text) {
      if (text == 0) {
        return '启动'
      } else if (text == 1) {
        return '暂停'
      } else if (text == 2) {
        return '删除'
      }
    },
  },
  {
    title: '操作',
    dataIndex: 'actionProduct',
    align: 'center',
    scopedSlots: { customRender: 'actionProduct' },
  },
]
const projectColumns = [
  {
    title: '项目名称',
    align: 'center',
    dataIndex: 'projectName',
  },
  {
    title: '产品名',
    align: 'center',
    dataIndex: 'productId_dictText',
  },
  {
    title: '广告主名称',
    align: 'center',
    dataIndex: 'advertiserId_dictText',
  },
  {
    title: '最高出价',
    align: 'center',
    dataIndex: 'maxBid',
    scopedSlots: {
      customRender: 'maxBid',
    },
  },
  {
    title: '最高转化出价',
    align: 'center',
    dataIndex: 'maxDeepCpaBid',
    scopedSlots: {
      customRender: 'maxDeepCpaBid',
    },
  },
  {
    title: '优化目标',
    align: 'center',
    dataIndex: 'bidType',
    scopedSlots: {
      customRender: 'bidType',
    },
  },
  {
    title: '转化目标',
    align: 'center',
    dataIndex: 'ocpxActionType',
    scopedSlots: {
      customRender: 'ocpxActionType',
    },
  },
  {
    title: '供应商',
    align: 'center',
    dataIndex: 'supplierCode_dictText',
  },
  {
    title: '销售',
    align: 'center',
    dataIndex: 'saleId_dictText',
  },
  {
    title: '运营负责人',
    align: 'center',
    dataIndex: 'responsibleId_dictText',
  },
  {
    title: '设计负责人',
    align: 'center',
    dataIndex: 'designResponsibleId_dictText',
  },
  {
    title: '操作',
    dataIndex: 'actionProject',
    align: 'center',
    scopedSlots: {
      customRender: 'actionProject',
    },
  },
]
export default {
  name: 'AdvertiserList',
  mixins: [JeecgListMixin],
  components: {
    AFormItem,
    JTreeSelect,
    JSelectUserByDep,
    JSelectDepart,
    JSelectUser,
  },
  data() {
    return {
      list: [],
      allIdUser: {},
      departDisabled: false, //是否是我的部门调用该页面
      users: this.userInfo().realname, //用户名称
      departmentId: this.userInfo().departId, //部门id
      description: '广告主信息表管理页面',
      visible: false,
      accountName: '',
      password: '',
      mode: 'login',
      showLogin: true,
      showAuthorization: false,
      authorizationType: 'kuaishou',
      loginType: 'kuaishou',
      form: this.$form.createForm(this),
      active: 'advertiser',
      advertiserName: '',
      advertiserId: '',
      productName: '',
      examinelList: [
        {
          value: '0',
          tab: '广告主列表',
        },
        {
          value: '1',
          tab: '产品列表',
        },
        {
          value: '2',
          tab: '项目列表',
        },
      ],
      // 表头
      columns: advertiserColumns,
      url: {
        list: '/ctop/advertiser/list',
        delete: '/ctop/advertiser/delete',
        deleteBatch: '/ctop/advertiser/deleteBatch',
        exportXlsUrl: 'ctop/advertiser/exportXls',
        importExcelUrl: 'ctop/advertiser/importExcel',
        bindAccountLoginUrl: '/ctop/bindAccountLogin/login',
        bindAuthorizationUrl: '/ctop/bindAccountAuth/authorization',
        getLoginInfo: '/ctop/bindAccount/getLoginInfo',
        userId: '/sys/user/generateUserId', // 引入生成添加用户情况下的url
        userWithDepart: '/sys/user/userDepartList', // 引入为指定用户查看部门信息需要的url
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  created() {
    this.queryParam.userId = this.userInfo().id
    this.getList(null)
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    getList(value) {
      var params = {}
      params.userId = this.userInfo().id
      params.pageSize = 50
      params.pageNo = 1
      params.name = value
      console.log(params)
      getAction('/ctop/advertiser/list', params)
        .then((res) => {
          if (res.success) {
            console.log(res)
            this.list = res.result.records
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    handleEditElse(item, type) {
      if (type == 'product') {
        this.$refs.modalFormTwo.edit(item)
        this.$refs.modalFormTwo.title = '编辑'
        this.$refs.modalFormTwo.disableSubmit = false
      } else if (type == 'project') {
        this.$refs.modalFormThree.edit(item)
        this.$refs.modalFormThree.title = '编辑'
        this.$refs.modalFormThree.disableSubmit = false
      }
    },
    clear(type) {
      this.queryParam.name = null
      this.queryParam.advertiserId = null
      this.queryParam.productId = null
      this.queryParam.id = null
      this.queryParam.productName = null
      this.queryParam.projectName = null
      this.allIdUser = {}
      this.loadData(1)
    },
    addNew() {
      if (this.active == 'advertiser') {
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      } else if (this.active == 'product') {
        if (this.queryParam.advertiserId) {
          this.$refs.modalFormTwo.add({ advertiserId: this.queryParam.advertiserId })
        } else {
          this.$refs.modalFormTwo.add()
        }
        this.$refs.modalFormTwo.title = '新增'
        this.$refs.modalFormTwo.disableSubmit = false
      } else if (this.active == 'project') {
        this.$refs.modalFormThree.add({
          advertiserId: this.queryParam.advertiserId
            ? this.queryParam.advertiserId
            : this.advertiserId
            ? this.advertiserId
            : undefined,
          productId: this.queryParam.productId ? this.queryParam.productId : undefined,
        })
        this.$refs.modalFormThree.title = '新增'
        this.$refs.modalFormThree.disableSubmit = false
      }
    },
    toProduct(item, key) {
      if (key == 'product') {
        this.queryParam.advertiserId = item.id
        this.advertiserName = item.name
        this.queryParam.productId = null
        this.productName = null
        this.queryParam.productName = null
        this.callbackTwo('product')
      } else if (key == 'project') {
        this.queryParam.productId = item.id
        this.productName = item.productName
        this.advertiserId = item.advertiserId
        this.queryParam.projectName = null
        this.callbackTwo('project')
      }
    },
    callbackTwo(key) {
      this.active = key
      if (key == 'advertiser') {
        this.columns = advertiserColumns
        this.url.list = '/ctop/advertiser/list'
        this.url.delete = '/ctop/advertiser/delete'
      } else if (key == 'product') {
        this.columns = productColumns
        this.url.list = '/ctop/product/list'
        this.url.delete = '/ctop/product/delete'
      } else if (key == 'project') {
        this.columns = projectColumns
        this.url.list = '/ctop/project/list'
        this.url.delete = '/ctop/project/delete'
      }
      this.searchQueryOne()
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    searchRe() {
      this.queryParam.name = null
      this.queryParam.advertiserId = null
      this.queryParam.productId = null
      this.queryParam.id = null
      this.queryParam.productName = null
      this.queryParam.projectName = null
      this.allIdUser = {}
      this.callbackTwo('advertiser')
    },
    searchQueryOne() {
      console.log(this.allIdUser)
      if (this.allIdUser.key) {
        if (this.active == 'advertiser') {
          this.queryParam.advertiserId = null
          this.queryParam.id = this.allIdUser.key
        } else {
          this.queryParam.id = null
          this.queryParam.advertiserId = this.allIdUser.key
        }
        this.advertiserName = this.allIdUser.label
      } else {
        // this.queryParam.advertiserId = null
        // this.queryParam.productId = null
        // this.queryParam.id = null
      }
      this.searchQuery()
    },
    handleSubmit() {
      let params = {}
      params.advertiserId = this.record.id
      params.advertiser_name = this.record.name
      params.userId = this.userInfo().id
      params.userName = this.userInfo().realname
      params.projectId = this.record.projectId
      params.projectName = this.record.projectName

      // 触发表单验证
      this.form.validateFields((err) => {
        if (!err) {
          if (this.mode == 'login') {
            params.accountName = this.accountName
            params.password = this.password
            params.loginType = this.loginType
            if (this.loginType == 'kuaishou') {
              params.mediaId = 2
            } else if (this.loginType == 'bytedance') {
              params.mediaId = 1
            }
            postAction(this.url.bindAccountLoginUrl, params).then((res) => {
              if (res.success) {
                alert('绑定成功')
                this.accountName = ''
                this.password = ''
                this.loginType = ''
              } else {
                alert(res.message)
              }
            })
          }
          // 授权登录
          if (this.mode == 'authorization') {
            params.authorizationType = this.authorizationType
            if (this.authorizationType == 'kuaishou') {
              params.mediaId = 2
            } else if (this.authorizationType == 'bytedance') {
              params.mediaId = 1
            }
            postAction(this.url.bindAuthorizationUrl, params).then((res) => {
              if (res.success) {
                window.open(res.message, '_blank')
              } else {
                alert('绑定失败')
              }
            })
          }
        }
      })
    },

    onChageLogin() {
      console.log(this.mode)
      if (this.mode == 'login') {
        this.showLogin = true
        this.showAuthorization = false
      } else {
        this.showLogin = false
        this.showAuthorization = true
      }
    },
    showModal(record) {
      this.record = record
      this.visible = true
    },

    handleCancel() {
      this.close()
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
