<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="平台名称" prop="thirdName">
        <el-input
          v-model="queryParams.thirdName"
          placeholder="请输入平台名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="平台类型" prop="thirdType">
        <el-select v-model="queryParams.thirdType" placeholder="请选择平台类型" clearable size="small">
          <el-option
            v-for="dict in thirdTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:third:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:third:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:third:delete']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:third:export']"
        >导出</el-button>
      </el-col> -->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="thirdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" width="55" align="center" prop="id" />
      <el-table-column label="平台名称" width="80px" align="center" prop="thirdName" />
     
      <el-table-column  label="平台类型" width="80px" align="center" prop="thirdType">
        <template slot-scope="scope">
             <template v-for="(item, index) in thirdTypeOptions">
                <el-tag prop="thirdType" :key="'thirdType'+index"   v-if="scope.row.thirdType==item.dictValue">{{item.dictLabel}}</el-tag>
             </template>
        </template>
      </el-table-column>
      <el-table-column label="授权账号" width="120px" align="center" prop="account" />
      <el-table-column label="广告主ids" width="200" align="center" prop="advertiserIds">
        <template slot-scope="scope">
             {{  getSubStr(scope.row.advertiserIds)   }}   
        </template>
      </el-table-column>
      <el-table-column label="广告主名称" width="300" align="center" prop="advertiserNames">
        <template slot-scope="scope">
             {{  getSubStr(scope.row.advertiserNames)   }}   
        </template>
      </el-table-column>
      <!-- <el-table-column label="appid"  align="center" prop="appId" />
      <el-table-column label="secret" align="center" prop="appSecret" /> -->

      <el-table-column label="accessToken" align="center" prop="accessToken" />
      <el-table-column label="refreshToken" align="center" prop="refreshToken" />
      <el-table-column  label="授权状态" width="90px" align="center" prop="status">
        <template slot-scope="scope">
             <template v-for="(item, index) in statusOptions">
                <el-tag prop="status" :key="'status'+index"  :type="scope.row.accessStatus==1?'success':'info'"   v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
             </template>
        </template>
      </el-table-column>

      <el-table-column  label="accessToken状态"   align="center" prop="accessStatus">
        <template slot-scope="scope">
            <el-tag prop="accessStatus" :key="'accessStatus'+index" v-for="(item, index) in accessStatusOptions"    :type="scope.row.accessStatus==1?'success':'danger'"   v-if="scope.row.accessStatus==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>
 
      <el-table-column  label="refreshToken状态"   align="center" prop="refreshStatus">
        <template slot-scope="scope">
            <el-tag prop="refreshStatus" :key="'refreshStatus'+index" v-for="(item, index) in refreshStatusOptions"  :type="scope.row.refreshStatus==1?'success':'danger'"   v-if="scope.row.refreshStatus==item.dictValue">{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column label="refreshToken状态" align="center" prop="refreshStatus" :formatter="refreshStatusFormat" /> -->

      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-paperclip"
            @click="handleAuth(scope.row)"
          >授权</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-suitcase"
            @click="getAdvertisers(scope.row)"
          >广告主</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-operation"
            @click="handleFeiyuCrmLineList(scope.row)"
          >线索</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:third:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:third:remove']"
          >删除</el-button>
   
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户线索三方平台对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="平台名称" prop="thirdName">
          <el-input v-model="form.thirdName" placeholder="请输入平台名称" />
        </el-form-item>
        <el-form-item label="平台类型" prop="thirdType">
          <el-select v-model="form.thirdType" placeholder="请选择平台类型">
            <el-option
              v-for="dict in thirdTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平台appid" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入平台appid" />
        </el-form-item>
        <el-form-item label="平台secret" prop="appSecret">
          <el-input v-model="form.appSecret" placeholder="请输入平台secret" />
        </el-form-item>
        <el-form-item label="授权账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入授权账号" />
        </el-form-item>
        <el-form-item label="是否授权">
          <el-radio-group  v-model="form.status">
            <el-radio disabled
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
         <el-form-item label="accessToken" prop="accessToken">
          <el-input  v-model="form.accessToken" placeholder="请输入三方平台access_token" />
        </el-form-item>
        <el-form-item label="refreshToken" prop="refreshToken">
          <el-input  v-model="form.refreshToken" placeholder="请输入三方平台refresh_token" />
        </el-form-item>

        <el-form-item label="accessToken状态" prop="accessStatus">
          <el-select v-model="form.accessStatus"  placeholder="accessToken状态">
            <el-option
              v-for="dict in accessStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="refreshToken状态" prop="refreshStatus">
          <el-select v-model="form.refreshStatus"  placeholder="refreshToken状态">
            <el-option
              v-for="dict in refreshStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="授权广告Ids" prop="advertiserIds" v-if="form.id!=null">
          <el-input type="textarea" size="medium" :rows="4"  v-model="form.advertiserIds" placeholder="请输入授权广告Ids" />
        </el-form-item>
        <el-form-item label="授权广告名称" prop="advertiserNames" v-if="form.id!=null">
          <el-input type="textarea" size="medium" :rows="4" v-model="form.advertiserNames" placeholder="请输入授权广告名称" />
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog :title="feiyuCrmLineList.title" :visible.sync="feiyuCrmLineList.open" width="1200px" append-to-body>
      <feiyu-crm-line-list  ref="feiyuCrmLineList" @close="closeFeiyuCrmList"></feiyu-crm-line-list>
    </el-dialog>


  </div>
</template>

<script>
import { listThird, getThird, delThird, addThird, updateThird, exportThird,saveFeiyuAuth,getAdvertisers } from "@/api/crm/third";
import feiyuCrmLineList from '../components/feiyuCrmLineList.vue';
 
export default {
  name: "Third",
  components: { feiyuCrmLineList },
  data() {
    return {
      feiyuCrmLineList:{
        title:"飞鱼线索客户",
        open:false,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户线索三方平台表格数据
      thirdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      state:null,
      authCode:null,
      // 平台类型字典
      thirdTypeOptions: [],
      // 状态  0未授权 1 已授权字典
      statusOptions: [],
      // token状态  0未获取  1已生效  2已过期字典
      accessStatusOptions: [],
      // token状态  0未获取  1已生效  2已过期字典
      refreshStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        thirdName: null,
        thirdType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
          thirdName: [
            { required: true, message: "请输入平台名称", trigger: "blur" }
          ],
           thirdType: [
            { required: true, message: "请输入平台类型", trigger: "blur" }
          ],
           appId: [
            { required: true, message: "请输入appId", trigger: "blur" }
          ],
           appSecret: [
            { required: true, message: "请输入appSecret", trigger: "blur" }
          ],
      }
    };
  },
  created() {
   
    this.getDicts("crm_third_type").then(response => {
      this.thirdTypeOptions = response.data;
    });
    this.getDicts("crm_third_status").then((response) => {
        this.statusOptions = response.data;
    });

    this.getDicts("crm_third_token_status").then(response => {
      this.accessStatusOptions = response.data;
    });
    this.getDicts("crm_third_token_status").then(response => {
      this.refreshStatusOptions = response.data;
    });
    this.getList();
    this.initParams();
  },
  methods: {
    /** 查询客户线索三方平台列表 */
    getList() {
      this.loading = true;
      listThird(this.queryParams).then(response => {
          this.thirdList = response.rows;
          console.log("qxj thirdList",JSON.stringify(this.thirdList));
          this.total = response.total;
          this.loading = false;
      });
    },

    initParams(){
        if(!!this.$route.query.state){
            this.state=this.$route.query.state;
        }
        if(!!this.$route.query.auth_code){
            this.authCode=this.$route.query.auth_code;
            setTimeout(() => {
              this.saveFeiyuAuth();
            }, 1000);
        }
    },

    // 平台类型字典翻译
    thirdTypeFormat(row, column) {
      return this.selectDictLabel(this.thirdTypeOptions, row.thirdType);
    },
    
    // token状态  0未获取  1已生效  2已过期字典翻译
    accessStatusFormat(row, column) {
      return this.selectDictLabel(this.accessStatusOptions, row.accessStatus);
    },
    // token状态  0未获取  1已生效  2已过期字典翻译
    refreshStatusFormat(row, column) {
      return this.selectDictLabel(this.refreshStatusOptions, row.refreshStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        thirdName: null,
        thirdType: null,
        appId: null,
        appSecret: null,
        account: null,
        status: '0',
        accessStatus: null,
        refreshStatus: null,
        accessToken: null,
        refreshToken: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户线索三方平台";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getThird(id).then(response => {
        this.form = response.data;
        this.form.thirdType = response.data.thirdType.toString();
        this.open = true;
        this.title = "修改客户线索三方平台";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateThird(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addThird(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除客户线索三方平台编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delThird(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有客户线索三方平台数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportThird(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleAuth(row){
        var scopeUrl="";
        if(row.thirdType==1){
            if (process.env.NODE_ENV === "development"){
                scopeUrl="https://open.oceanengine.com/audit/oauth.html?app_id="+row.appId+"&state="+row.id+"&redirect_uri=http%3A%2F%2Flocalhost%3A1024%2Fcustomer%2FfeiyuOauthCallback/";
            }else{
                scopeUrl="https://open.oceanengine.com/audit/oauth.html?app_id="+row.appId+"&state="+row.id+"&redirect_uri=http%3A%2F%2Fadmin.yjf.runtzh.com%2Fcustomer%2FfeiyuOauthCallback%2F";
            }
        }
        //scopeUrl=encodeURI(scopeUrl)
        console.log("qxj process.env.NODE_ENV:",process.env.NODE_ENV);
        window.location.href = scopeUrl;
    },
    saveFeiyuAuth(){
        var data={"authCode":this.authCode,"thirdId":parseInt(this.state)};
        saveFeiyuAuth(data).then(response => {
            if (response.code === 200) {
                this.msgSuccess("授权成功");
                this.getList();
            }
        });
    },
    getAdvertisers(row){
        getAdvertisers(row).then(response => {
            if (response.code === 200) {
                this.msgSuccess("获取成功");
                this.getList();
            }
        });
    },
    handleFeiyuCrmLineList(row){
      //this.feiyuCrmLineList.title=row.thirdName;
      this.feiyuCrmLineList.open=true;
      var that=this;
      setTimeout(() => {
            that.$refs.feiyuCrmLineList.getData(row);
      }, 200);
    },
    closeFeiyuCrmList(){
       this.feiyuCrmLineList.open=false;
       this.getList();
    },
    getSubStr(sorstr){
      var formatStr="";
       if(!!sorstr){
          formatStr=sorstr.length>200?sorstr.substr(0,200)+"...":sorstr;
       }
       return formatStr;
    }
  }
};
</script>
