<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="公司名称">
        <!-- 修改为多选搜索框 -->
        <el-select
          v-model="queryParams.companyIds"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请输入公司名称搜索"
          :remote-method="searchCompanies"
          :loading="companySearchLoading"
          style="width: 220px"
          clearable
          size="small"
        >
          <el-option
            v-for="item in companyOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <inline-tenant-selector @change="handleQuery" />
      <el-button type="primary" 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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleRecharge"
          v-hasPermi="['platform:traffic:charge']"
        >流量充值</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="trafficRecordList" @selection-change="handleSelectionChange">

      <el-table-column label="公司名称" align="center" prop="companyName" :show-overflow-tooltip="true" />

      <el-table-column label="流量余额" align="center" prop="balance" :formatter="formatBalance"/>

<!--      <el-table-column label="操作人员" align="center" prop="createBy" />

      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(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-money"
            @click="handleRechargeCompany(scope.row)"
            v-hasPermi="['platform:traffic:charge']"
          >充值</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="rechargeTitle" :visible.sync="rechargeOpen" width="500px" append-to-body :before-close="resetOption">
      <el-form ref="rechargeForm" :model="rechargeForm" :rules="rechargeRules" label-width="100px">

        <el-form-item label="公司ID" prop="companyId" v-show="!isCompanyRecharge">
          <el-select
            v-model="rechargeForm.companyId"
            filterable
            remote
            placeholder="请输入公司名称搜索"
            :remote-method="searchCompanies"
            :loading="companySearchLoading"
            @change="syncCompanyName"
            style="width: 220px"
            clearable
            size="small"
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.dictValue"
              :label="item.dictValue"
              :value="item.dictValue"
            >
            <span style="float: left">{{ item.dictValue }}</span>
            <span style="margin-left: 30px">{{ item.dictLabel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="rechargeForm.companyName" placeholder="请输入公司名称" size="small" disabled/>
        </el-form-item>


        <el-form-item label="充值金额" prop="chargeAmount">
          <el-input-number
            v-model="rechargeForm.chargeAmount"
            :min="1"
            :max="999999999"
            placeholder="请输入充值金额(元)"
            controls-position="right"
            style="width: 100%"
            @input="chargeAmountInput"
          />
          <span v-if="this.amountToTraffic" class="el-form-item__error"> 约充值 {{ this.amountToTraffic }}流量 </span>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="rechargeForm.remark"
            type="textarea"
            placeholder="请输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRechargeForm">确 定</el-button>
        <el-button @click="cancelRecharge">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTrafficRecords, rechargeTraffic, trafficConversion } from '@/api/company/traffic'
import { allList } from '@/api/company/company'
import { resetForm } from '@/utils/common'
import { delAdIqiyiAccount } from '@/api/ad/AdIqiyiAccount'

import InlineTenantSelector from "@/components/InlineTenantSelector"

export default {
  name: "CompanyTraffic",
  data() {
    return {
      amountToTraffic: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流量记录表格数据
      trafficRecordList: [],
      // 弹出层标题
      rechargeTitle: "",
      // 是否显示充值弹出层
      rechargeOpen: false,
      // 公司搜索相关
      companySearchLoading: false,
      companyOptions: [],
      isCompanyRecharge: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        companyIds: [], // 修改为数组
        createTimeStart: null,
        createTimeEnd: null
      },
      // 流量充值表单参数（保持不变）
      rechargeForm: {
        companyId: null,
        companyName: null,
        chargeAmount: null,
        remark: null
      },
      // 流量详情数据
      detailData: {},
      // 表单校验（保持不变）
      rechargeRules: {
        companyId: [
          { required: true, message: "公司ID不能为空", trigger: "blur" }
        ],
        chargeAmount: [
          { required: true, message: "充值金额不能为空", trigger: "blur" },
          { type: "number", min: 1, message: "充值金额必须大于0", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    resetForm,
    resetOption(){
      this.rechargeOpen = false;
      this.companyOptions = [];
      this.rechargeForm = {};
    },
    /** 查询流量记录列表 */
    getList() {
      this.loading = true;

      listTrafficRecords(this.queryParams).then(response => {
        this.trafficRecordList = response.rows;
        console.log(this.trafficRecordList)
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 流量计算*/
    chargeAmountInput() {
      if(!this.rechargeForm.chargeAmount){
        this.amountToTraffic = 0;
        return;
      }
      trafficConversion({traffic:this.rechargeForm.chargeAmount}).then(
        response => {
          this.amountToTraffic = response.data;
          //对流量值进行判断，换算成GB或TB
          if(!this.amountToTraffic){
            this.amountToTraffic =  "0 KB";
          }
          if(this.amountToTraffic < 1024){
            this.amountToTraffic =  this.amountToTraffic + " KB";
          }
          else if(this.amountToTraffic < 1024 * 1024){
            this.amountToTraffic = (this.amountToTraffic / 1024).toFixed(2) + " MB";
          }
          else if(this.amountToTraffic < 1024 * 1024 * 1024){
            this.amountToTraffic = (this.amountToTraffic / (1024 * 1024)).toFixed(2) + " GB";
          }
          else{
            this.amountToTraffic = (this.amountToTraffic / (1024 * 1024 * 1024)).toFixed(2) + " TB";
          }
        }
      )
    }
    ,
    /** 搜索公司 */
    searchCompanies( query) {
      allList().then(response => {
        this.companyOptions = response.rows.filter(item => item.dictLabel.includes(query));
        this.companySearchLoading = false;
      }).catch(()=>{
        this.companySearchLoading = false;
      });
    },
    syncCompanyName(){
      if(!this.rechargeForm.companyId){
        this.rechargeForm.companyName = null;
      }
      this.rechargeForm.companyName = this.companyOptions.filter(item => item.dictValue === this.rechargeForm.companyId)[0].dictLabel;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.rechargeForm = {};
      this.handleQuery();
    },

    formatBalance(row){
      //对流量值进行判断，换算成GB或TB
      if(!row.balance){
        return "0 KB";
      }
      const absBalance = Math.abs(row.balance); // 获取绝对值
      if(absBalance < 1024){
        return row.balance + " KB";
      }
      else if(absBalance < 1024 * 1024){
        return (row.balance / 1024).toFixed(2) + " MB";
      }
      else if(absBalance < 1024 * 1024 * 1024){
        return (row.balance / (1024 * 1024)).toFixed(2) + " GB";
      }
      else{
        return (row.balance / (1024 * 1024 * 1024)).toFixed(2) + " TB";
      }
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 流量充值按钮操作 */
    handleRecharge() {
      this.rechargeTitle = "流量充值";
      this.resetForm("rechargeForm");
      this.rechargeForm = {};
      this.companyOptions = [];
      this.isCompanyRecharge = false;
      this.rechargeForm.operationType = 1; // 默认充值
      this.rechargeOpen = true;
    },/** 流量充值按钮操作 */
    handleRechargeCompany(row) {
      this.rechargeTitle = "流量充值";
      this.resetForm("rechargeForm");
      this.rechargeForm = {};
      this.companyOptions = [];
      this.isCompanyRecharge = true;
      this.rechargeForm.companyId = row.companyId;
      this.rechargeForm.companyName = row.companyName;
      this.rechargeForm.operationType = 1; // 默认充值
      this.rechargeOpen = true;
    },

    /** 提交流量充值 */
    submitRechargeForm() {
      this.$refs["rechargeForm"].validate(valid => {
        if (valid) {
          //添加confirm提示
          this.$confirm('确定要为 '+this.rechargeForm.companyName+' 充值 '+this.rechargeForm.chargeAmount+' 元吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            return rechargeTraffic(this.rechargeForm);
          }).then(response => {
            if(response.code === 200){
              this.msgSuccess("充值成功");
            }else{
              this.msgError(response.msg);
            }
            this.rechargeOpen = false;
            this.getList();
          }).catch(() => {});
        }
      });
    },

    /** 取消充值 */
    cancelRecharge() {
      this.rechargeOpen = false;
      this.resetForm("rechargeForm");
      this.rechargeForm = {};
    }
  }
};
</script>

<style scoped>

.mb8 {
  margin-bottom: 8px;
}
</style>
