<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-select
                placeholder="请选择所属人"
                showSearch
                optionFilterProp="children"
                style="width: 100%"
                :filterOption="filterOption"
                v-model="queryParam.userId"
                v-if="userInfo().username == 'admin'"
                @search="search"
                @focus="getAllUserList"
              >
                <a-select-option
                  v-for="appModel in optionsAll"
                  :key="appModel.userId + new Date().getTime()"
                  :value="appModel.userId"
                  >{{ appModel.realName }}</a-select-option
                >
              </a-select>
              <a-input placeholder="请输入所属人" v-model="queryParam.userName" v-else></a-input>
            </a-form-item>
          </a-col>
          <template>
            <a-col :md="8" :sm="8">
              <a-form-item label="广告主名称">
                <a-input placeholder="请输入广告主名称" v-model="queryParam.advertiserName"></a-input>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="8" :sm="8">
            <a-form-item label="账户状态">
              <a-select placeholder="请选择账户状态" v-model="queryParam.accountStatus">
                <a-select-option :value="0">开启</a-select-option>
                <a-select-option :value="1">关闭</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-item label="项目名称">
              <a-select
                v-model="queryParam.projectId"
                showSearch
                optionFilterProp="children"
                :filterOption="filterOption"
                @focus="getParticipateList"
                @search="getParticipateList"
              >
                <a-select-option :value="item.projectId" v-for="item of dataElse" :key="item.id">
                  {{
                    item.mediaId == '1'
                      ? '头条'
                      : item.mediaId == '2'
                      ? '快手'
                      : item.mediaId == '3'
                      ? '头条内广'
                      : '快手内广'
                  }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.projectName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-item label="账号id">
              <a-input placeholder="请输入账号id" v-model="queryParam.accountId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <br />
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <span slot="accountStatus" slot-scope="text, record">
          <!-- {{ text == 0 ? '启用' : '禁用' }} -->

          <a-switch v-model="record.accountStatus == 0 ? true : false" @change="onChangeSwitch(record)" />
        </span>
        <span slot="deleteComment" slot-scope="text, record">
          <!-- {{ text == 0 ? '启用' : '禁用' }} -->

          <a-switch v-model="record.deleteComment == 0 ? true : false" @change="deleteCommentChangeSwitch(record)" />
        </span>
        <span slot="mediaId" slot-scope="text">{{ text == 1 ? '头条' : '快手' }}</span>

        <div slot="authName" slot-scope="text, record">
          <span>{{ text }}</span>
          <a-button size="small" @click="renew(record)" style="float: right" :loading="record.showVideo"> 更新 </a-button>
          <!-- showVideo -->
        </div>

        <span slot="action" slot-scope="text, record">
          <!-- <a @click="account(record)">转移项目</a>

          <a-divider type="vertical" />
          <a @click="project(record)">转让账户</a>

          <a-divider type="vertical" /> -->
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" v-show="roleCode == 'admin'" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" v-show="roleCode == 'admin'">
            <a>删除</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a-dropdown :trigger="['click']">
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item key="0">
                <a @click="account(record)">转移项目</a>
              </a-menu-item>
              <a-menu-item key="1">
                <a @click="project(record)">转让账户</a>
              </a-menu-item>
             
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <userAllocation-modal ref="modalForm" @ok="modalFormOk"></userAllocation-modal>
    <!--  添加项目成员 -->
    <a-modal title="账户转让" v-model="visibleAdd" @ok="handleOkAdd" :confirmLoading="confirmLoading" :width="800">
      <a-form :form="form">
        <a-form-item
          label="转户人"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          <a-select
            v-decorator="['transferor']"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            style="width: 100%"
            disabled
          >
            <a-select-option :value="item.userId" v-for="(item, index) of options" :key="index">{{
              item.realName
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="受让人"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          <a-select
            v-decorator="['assignee', { rules: [{ required: true, message: '请选择受让人' }] }]"
            placeholder="请选择受让人"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            style="width: 100%"
          >
            <a-select-option :value="item.userId" v-for="(item, index) of options" :key="index">{{
              item.realName
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="转户人绩效截止日期"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          <a-date-picker
            v-decorator="['transferorDate', { rules: [{ required: true, message: '请选择转户人绩效截止日期' }] }]"
          />
          <!-- , { initialValue:moment(new Date(), 'YYYY-MM-DD') } -->
        </a-form-item>
        <a-form-item
          label="受让人绩效开始日期"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          {{!!getData('transferorDate')?moment(getData('transferorDate')).add(1,"days").format("YYYY-MM-DD"):'-'}}
          <!-- <a-date-picker
            v-decorator="['assigneeDate', { rules: [{ required: true, message: '请选择受让人绩效截止日期' }] }]"
          /> -->
        </a-form-item>
        <!-- 
        <a-form-item
          label="账号："
          :label-col="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapper-col="{ xs: { span: 24 }, sm: { span: 16 } }"
          v-show="mode == 'login'"
        >
          <a-input v-model="accountName" placeholder="请输入账户名" />
        </a-form-item>
        -->
      </a-form>
    </a-modal>
    <a-modal
      title="项目转移"
      v-model="visibleAccount"
      @ok="handleOkAccount"
      :confirmLoading="accountLoading"
      :width="800"
    >
      <a-form :form="formAccount">
        <a-form-item
          label="原项目"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          {{projectName}}
        </a-form-item>
        <a-form-item
          label="转移项目"
          :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapperCol="{ xs: { span: 24 }, sm: { span: 16 } }"
        >
          <!-- <a-select
            v-decorator="[
              'projectNewId', // 给表单赋值或拉取表单时，该input对应的key
              { rules: [{ required: true, message: '请选择项目!' }] },
            ]"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
          >
            <a-select-option :value="item.projectId" v-for="item of dataElse" :key="item.id">
              {{ item.projectName }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                item.mediaId == '1'
                  ? '头条'
                  : item.mediaId == '2'
                  ? '快手'
                  : item.mediaId == '3'
                  ? '头条内广'
                  : '快手内广'
              }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.advertiserName }}
            </a-select-option>
          </a-select> -->
          <a-select
            v-decorator="[
                'projectNewId', // 给表单赋值或拉取表单时，该input对应的key
                { rules: [{ required: true, message: '请选择项目!' }] },
            ]"
            @focus="getParticipateList"
            showSearch
            optionFilterProp="children"
            :filterOption="filterOption"
            @search="getParticipateList"
          >
              <a-select-option :value="item.projectId" v-for="item of dataElse" :key="item.id">
                  {{ item.projectName }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                      item.mediaId == '1'
                      ? '头条'
                      : item.mediaId == '2'
                      ? '快手'
                      : item.mediaId == '3'
                      ? '头条内广'
                      : '快手内广'
                  }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.advertiserName }}
              </a-select-option>
          </a-select>
        </a-form-item>
        <!-- 
        <a-form-item
          label="账号："
          :label-col="{ xs: { span: 24 }, sm: { span: 5 } }"
          :wrapper-col="{ xs: { span: 24 }, sm: { span: 16 } }"
          v-show="mode == 'login'"
        >
          <a-input v-model="accountName" placeholder="请输入账户名" />
        </a-form-item>
        -->
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import UserAllocationModal from './modules/UserAllocationModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { mapGetters } from 'vuex'
import { httpAction, getAction, deleteAction } from '@/api/manage'


import moment from 'moment'
import { postAction } from '../../../api/manage'
import qs from 'qs'
export default {
  name: 'UserAllocationList',
  mixins: [JeecgListMixin],
  components: {
    UserAllocationModal,
  },
  data() {
    return {
      description: '账号绑定管理页面',
      visibleAdd: false,
      visibleAccount: false,
      options: [],
      optionsAll: [],
      dataElse: [],
      // 表头
      columns: [
        {
          title: '账号所属人',
          align: 'center',
          dataIndex: 'userName',
        },
        {
          title: '授权',
          align: 'center',
          dataIndex: 'accountId',
        },
        {
          title: '广告主名称',
          align: 'center',
          dataIndex: 'advertiserId_dictText',
        },
        {
          title: '项目名称',
          align: 'center',
          dataIndex: 'projectId_dictText',
        },
        //    {
        //     title: '输入账号  --登录',
        //     align:"center",
        //     dataIndex: 'accountName'
        //    },
        {
          title: '授权名称',
          align: 'center',
          dataIndex: 'authName',
          scopedSlots: {
            customRender: 'authName',
          },
        },
        {
          title: '平台类型',
          align: 'center',
          dataIndex: 'mediaId',
          scopedSlots: {
            customRender: 'mediaId',
          },
        },
        {
          title: '预警金额',
          align: 'center',
          dataIndex: 'warningAmount',
        },
        {
          title: '预警比例',
          align: 'center',
          dataIndex: 'warningProportion',
        },
        // accountStatus:0启用；1禁用
        {
          title: '账户状态',
          dataIndex: 'accountStatus',
          align: 'center',
          scopedSlots: {
            customRender: 'accountStatus',
          },
        },

        {
          title: '系统名称',
          dataIndex: 'systemType',
          align: 'center',
        },
        {
          title: '是否开启删评论',
          dataIndex: 'deleteComment',
          align: 'center',
          width:80,
          scopedSlots: {
            customRender: 'deleteComment',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 160,
          scopedSlots: {
            customRender: 'action',
          },
        },
      ],
      url: {
        list: '/ctop/userAllocation/list',
        delete: '/ctop/userAllocation/delete',
        deleteBatch: '/ctop/userAllocation/deleteBatch',
        exportXlsUrl: 'ctop/userAllocation/exportXls',
        importExcelUrl: 'ctop/userAllocation/importExcel',
      },
      confirmLoading: false,
      accountLoading: false,
      projectId: '',
      projectName:'',
      accountId: '',
      mediaId: '',
      form: this.$form.createForm(this),
      formAccount: this.$form.createForm(this),
      roleCode: localStorage.getItem('roleCode'),
      dataElse: [],
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  mounted() {
    this.getParticipateList(null)
  },
  methods: {
    renew(item) {
      console.log(item)
      item.showVideo = true
      getAction('/ctop/userAllocation/updateAuthName', { accountId: item.accountId, mediaId: item.mediaId }).then(
        (res) => {
          if (res.success) {
            this.loadData()
          } else {
            this.$message.error('更新数据失败，请稍后重试！！！')
            item.showVideo = false
          }
        }
      )
    },
    moment,
    search(value) {
      this.optionsAll = []
      if (value != '') {
        // this.options = this.list.filter(item => {
        //   var data = item.realName + ' ' + item.roleName
        //   return data.toLowerCase().indexOf(value.toLowerCase()) > -1
        // })
        // this.options = [...this.options]
        this.getAllUserList(value)
      } else {
        this.getAllUserList()
      }
    },
    getAllUserList(value) {
      getAction('/sys/user/getAllUserList', { pageSize: 50, pageNo: 1, userName: value }).then((res) => {
        if (res.success) {
          this.optionsAll = res.result.list
        }
      })
    },
    onChangeSwitch(item) {
      var params = {}
      params.id = item.id
      params.accountStatus = item.accountStatus == 0 ? 1 : 0

      httpAction('/ctop/userAllocation/edit', params, 'put').then((res) => {
        if (res.success) {
          this.loadData()
        }
      })
    },
    deleteCommentChangeSwitch(record){
      console.log(record)
      var params = {}
      params.accountId = record.accountId
      params.switchType = record.deleteComment ==0 ? 1 : 0

      postAction('/ctop/userAllocation/onOrOffDeleteComment', qs.stringify(params)).then((res) => {
        if (res.success) {
          this.loadData()
        }
      })
    },
    getData(className) {
      return this.form.getFieldValue(className)
    },
    getParticipateList(value) {
      // getAction('/ctop/projectMember/participateList', {
      //   userId: this.userInfo().id,
      // }).then((res) => {
      //   if (res.code == 0) {
      //     this.dataElse = res.result
      //   }
      // })
      getAction('/ctop/projectMember/participateListV2', {
        userId: this.userInfo().id,
        pageSize: 100,
        pageNo: 1,
        projectName: value,
      }).then(res => {
          if (res.code == 0) {
              let defaultData = res.result.records;
              this.dataElse = defaultData;
          }
      });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    getALLperson() {
      getAction('/sys/user/getAllUserListByCompany', {
        userId: this.userInfo().id,
      }).then((res) => {
        if (res.success) {
          this.options = res.result
        }
      })
    },
    project(item) {
      this.visibleAdd = true
      this.accountId = item.accountId
      this.projectId = item.projectId

      setTimeout(() => {
        this.form.setFieldsValue({
          transferor: item.userId,
        })
      }, 0)
      this.getALLperson()
    },
    account(item) {
      this.visibleAccount = true
      this.accountId = item.accountId
      this.projectId = item.projectId
      this.projectName = item.projectId_dictText
      this.accountLoading = false
      // setTimeout(() => {
      //   this.formAccount.setFieldsValue({
      //     projectId: item.projectId,
      //   })
      // }, 0)
    },
    handleOkAccount(e) {
      this.formAccount.validateFieldsAndScroll((err, values) => {
        if (err) {
          // 这里做逻辑处理
        } else {
          this.accountLoading = true
          var params = qs.stringify({
            projectId: values.projectNewId,
            accountId: this.accountId,
          })
          postAction('/ctop/projectTransferRecord/add', params).then((res) => {
            if (res.success) {
              this.accountLoading = false
              this.visibleAccount = false
              this.formAccount.resetFields()
              this.loadData()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    handleOkAdd(e) {
      this.form.validateFieldsAndScroll((err, values) => {
        if (err) {
          // 这里做逻辑处理
        } else {
          this.confirmLoading = true
          var params = {
            ...values,
          }
          params.transferorDate = moment(values.transferorDate).format('YYYY-MM-DD')
          params.assigneeDate = moment(values.transferorDate).add(1,"days").format("YYYY-MM-DD")
          params.projectId = this.projectId
          params.accountId = this.accountId
          params.status = 0
          postAction('/ctop/transferAccount/add', params).then((res) => {
            if (res.success) {
              this.confirmLoading = false
              this.visibleAdd = false
              this.form.resetFields()
            } else {
              this.confirmLoading = false
              this.$message.error(res.message)
            }
          })
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>