<template>
 <div class="sort pagePadding" style="padding-right: 20px;">
    <div class="table__wrapper" v-if="powers.some((i) => i == '001')">
      <div style="width:49%;margin-top:10px;">
        <div style="width: 100%;height:40px">
         <div style="display:inline-flex;align-items: center;">
           <el-input 
             size="mini" 
             placeholder="支付渠道名称"
             v-model="parmValue.paymentChannel['channel_name']"
             clearable
             @change="pageInfo.paymentChannel.curr = 1;parmValue.paymentChannel.page = 1;onSearchPaymentChannelGrossProfit()" 
           />
         </div>

         <div class="fr">
           <el-button size="mini" type="primary" @click="onSearchPaymentChannelGrossProfit">刷新</el-button>
         </div>
        </div>
          <div class="table-wrapper">
            <ex-table
              ref="paymentChannelRef"
              layout="total, prev, pager, next, jumper"
              v-loading="loadings.paymentChannel"
              :table="table"
              :data="datas.paymentChannel"
              :columns="paymentChannelColumns"
              :page="pageInfo.paymentChannel"
              :size="size"
              :row-key="row => row.id"
              @page-curr-change="handlePageChange"
              @page-size-change="handleSizeChange"
              @screen-reset="
                pageInfo.paymentChannel.curr = 1;
                parmValue.paymentChannel.page = 1;
                onSearchPaymentChannelGrossProfit();
              "
              @screen-submit="
                pageInfo.paymentChannel.curr = 1;
                parmValue.paymentChannel.page = 1;
                onSearchPaymentChannelGrossProfit();
              "
            >
              <template #selection="{scope}">
                  <el-radio  v-model="selectedRow" :label="scope.row"><i></i></el-radio>
              </template>
            </ex-table>
          </div>
      </div>


      <div style="width:49%;margin-top:10px">
         <div style="width:100%;height:40px">
           <div style="display:inline-flex;align-items: center;">
             <el-input size="mini" 
                v-model="parmValue.category['cat_name']"
                placeholder="一级分类名称" 
                clearable
               @change=" 
                 pageInfo.category.curr = 1;
                 parmValue.category.page = 1;
                 onSearchcategorylist()" 
              />
           </div>

           <div class="fr">
             <el-button size="mini" @click="parmValue.category.cat_name = '';onSearchcategorylist()">重置</el-button>
             <el-button size="mini" type="primary" @click="onSearchcategorylist">刷新</el-button>
           </div>
         </div>
         <div class="table-wrapper">
           <ex-table
               v-loading="loadings.category"
               v-if="powers.some((i) => i == '001')"
               :table="table"
               :data="datas.category"
               :columns="categoryColumns"
               :page="pageInfo.category"
               :size="size"
               :noPagination="true"
               @page-curr-change="value => handlePageChange(value,true)"
               @page-size-change="value => handleSizeChange(value,true)"
               @screen-reset="
                 pageInfo.category.curr = 1;
                 parmValue.category.page = 1;
                 onSearchcategorylist();
               "
               @screen-submit="
                 pageInfo.category.curr = 1;
                 parmValue.category.page = 1;
                 onSearchcategorylist();
               "
             >
               <template #rate="{scope}">
                 {{Number(scope.row.rate).toFixed(2)}}%
               </template>

               <template #channel_name>
                 {{selectedRow.channel_name}}
               </template>

               <template #operation="{ scope }">
                 <el-tooltip
                   v-if="powers.some((i) => i == '005')"
                   effect="dark"
                   content="修改"
                   placement="top"
                 >
                   <i class="el-icon-edit tb-icon" @click="setRate(scope.row,actionTypes.UPDATE)"></i>
                 </el-tooltip>
              </template>
            </ex-table>
         </div>
      </div>
     </div>

    <no-auth v-else />

    <!-- 弹窗 新增/修改 -->
    <add-edit-rate
      :id="modelRateId"
      :show-model="showRateModel"
      :sitem="sitemCategory"
      @refresh="onSearchcategorylist"
      @cancel="showRateModel = false"
      :paymentChannel="selectedRow || {}"
      :actionType="actionType"
    />
  </div>
</template>
<script>
import addEditRate from "./addEditRate";
import asyncRequest from "@/apis/service/serviceParam/paymentChannelGrossProfit";
import { statusList } from "@/assets/js/statusList";
import roleLevel from "@/assets/js/roleLevel";
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import { mapGetters } from "vuex";
import privateField from "@/mixins/privateField";
import { actionTypes } from "@/utils/actionType";

import { paymentChannelColumns,categoryColumns } from "./columns"
export default {
  name: "othsearchSort",
  mixins: [mixinPage, resToken, privateField],
  components: {
    addEditRate,
  },
  computed: {
    //组件SIZE设置
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const { btnList } = this.$store.getters;
      const tran = btnList.find((i) => i.menu_route == "paymentChannelGrossProfit") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      selectedRow:{},
      categoryColumns,
      paymentChannelColumns,
      actionTypes,
      actionType:'',
      isDetail: true,
      private_field: [],
      statusList: statusList,
      roleLevel: roleLevel,
      loading: false,
      sitem: {},
      showRateModel: false,
      modelRateId: "000",
      sitemCategory: {},
      titleList: [],
      loadings:{
        paymentChannel:false,
        category:false
      },
      datas:{
        paymentChannel:[],
        category:[]
      },
      parmValue: {
        paymentChannel:{
          page: 1, // 页码
          size: 15, // 每页显示条数
          channel_name:"",
        },
        category:{
          page: 1, // 页码
          size: 100, // 每页显示条数
          cat_name:"",
        }
      },
      // 状态
      statusOptions: [
        { id: "0", label: "禁用" },
        { id: "1", label: "启用" },
      ],
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
      },
      // 表格 - 分页
      pageInfo: {
        paymentChannel:{
          size: 15,
          curr: 1,
          total: 0,
        },
        category:{
          size: 100,
          curr: 1,
          total: 0,
        }        
      },
      // 表格 - 列参数
      columns: [
        {
          prop: "id",
          label: "ID",
          minWidth: "60px",
        },
        {
          prop: "channel_name",
          label: "支付渠道名称",
          width: "230px",
        },
        {
          prop: "status",
          label: "当前状态",
          width: "230px",
          _slot_:'status'
        },
        {
          prop: "创建人参数",
          label: "创建人",
          width: "230px",
        },
        {
          prop: "addtime",
          label: "创建时间",
          width: "260px",
        },
        {
          prop: "",
          label: "操作",
          fixed: "right",
          width: "60px",
          _noset_: true,
          _slot_: "operation",
        },
      ],
    };
  },
  watch:{
    selectedRow:{
      handler(value){
        if(JSON.stringify(value) === "{}"){
          this.datas.category = []
        }else{
          this.onSearchcategorylist()
        }
      }
    }
  },
  mounted() {
    this.parmValue.pid = "0";
    this.onSearchPaymentChannelGrossProfit()
  },
  methods: {
    async handlePageChange(val,isCategory = false) {
      const prop = isCategory ? 'category' : 'paymentChannel'
      this.parmValue[prop].page = val
      this.pageInfo[prop].curr = val
      if(!isCategory) this.selectedRow = {}
      await isCategory ? this.onSearchcategorylist() : this.onSearchPaymentChannelGrossProfit()
    },
    async handleSizeChange(val, isCategory = false) {
      const prop = isCategory ? 'category' : 'paymentChannel'
      this.parmValue[prop].page = 1
      this.pageInfo[prop].curr = 1
      this.pageInfo[prop].size = val
      this.parmValue[prop].size = val
      if(!isCategory) this.selectedRow = {}
      await isCategory ? this.onSearchcategorylist() : this.onSearchPaymentChannelGrossProfit()
    },
    handleSelectChange(rows){
      this.$refs.paymentChannelRef && this.$refs.paymentChannelRef.clearSelection();
      const selectedRow = rows.length > 0 ? rows[0] : null
      this.$refs.paymentChannelRef && selectedRow && this.$refs.paymentChannelRef.toggleRowSelection(selectedRow)
      this.selectedRow = selectedRow
    },
    restSearch() {
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.parmValue = {
        page: 1, // 页码
        size: 15, // 每页显示条数
        status: "",
        channel_name:"",
        创建人参数:""
      };
      this.onSearchPaymentChannelGrossProfit();
    },
    //设置毛利率
    setRate(row, actionType) {
      this.actionType = actionType
      this.modelRateId = row.id;
      this.sitemCategory = row;
      this.showRateModel = true;
    },

    async changeBreadcrumb(index) {
      if (index + 1 === this.titleList.length) {
        return;
      } else {
        this.parmValue.pid = this.titleList[index].id;
        this.parmValue.status = ""
        this.parmValue.cat_name = ""
        this.titleList = this.titleList.slice(0, index + 1);
      }
      
      this.parmValue.cat_name = "";
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.onSearchPaymentChannelGrossProfit();
    },

    async changeStatus(id, status) {
      await this.$confirm(`确定要改为${status + "" === "1" ? "禁用" : "启用"}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true;

          const model = {
            id,
            status: String(status) ? (String(status) === "1" ? "0" : "1") : "1",
            companyNo: this.currentCompany
          };

          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;

            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });

            await this.onSearchPaymentChannelGrossProfit();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.loading = false;
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },

    async onSearchPaymentChannelGrossProfit(){
      if (this.loadings.paymentChannel) return;

      // if (!this.currentCompany) {
      //   this.$message.warning("请选择公司！");
      //   this.datas.paymentChannel = []
      //   return;
      // }       
      // companyNo:this.currentCompany

      this.loadings.paymentChannel = true;
      const { code, data } = await asyncRequest.paymentChannelList({
        ...this.parmValue.paymentChannel,
      });

      if (code === 0) {
       const { list, count } = data ?? {};
       this.datas.paymentChannel = list ?? [];
       this.datas.category = []
       this.pageInfo.paymentChannel.total = count ?? 0;
       
       if(list.length > 0){
        this.selectedRow = list[0]
       }else{
        this.selectedRow = {}
      }


      }else if (code >= 100 && code <= 104) {
       await this.logout();
      }else {
       this.datas.paymentChannel = [];
       this.pageInfo.paymentChannel.total = 0;
      }
      this.loadings.paymentChannel = false;
    },

    async onSearchcategorylist(){
      if (this.loading) return;

      this.parmValue.companyNo = this.currentCompany;
      this.loadings.category = true;
      
      const { code, data } = await asyncRequest.categorylist({
        channel_id:this.selectedRow.id,
        ...this.parmValue.category
      });

      if (code === 0) {
       this.datas.category = data || []
       this.pageInfo.category.total = data.length
      }else if (code >= 100 && code <= 104) {
       await this.logout();
      }else {
       this.datas.category = [];
       this.pageInfo.category.total = 0;
      }

      this.loadings.category = false;
    },
    onCompanyChange(){
      this.selectedRow = {}
      this.onSearchPaymentChannelGrossProfit()
    }
  },
};
</script>

<style lang="scss" scoped>
.table__wrapper{
  display: flex;
  width: 100%;
  overflow:hidden;
  gap: 20px;
}

.table-wrapper{
  height: calc(100vh - 120px);
  overflow-x: auto;
}

.sort {
  .my-breadcrumb {
    .my-breadcrumb-item {
      float: left;
      span {
        height: 32px;
        line-height: 32px;
      }
      .label {
        padding: 0 5px 0 0;
        color: 010101;
      }
      .separator {
        color: #787878;
        font-size: 13px;
        padding: 0 5px 0 0;
      }
      &:last-child {
        .label {
          color: #787878;
        }
      }
      &:hover {
        cursor: pointer;
      }
      &:last-child {
        cursor: default;
      }
      &:only-child {
        cursor: pointer;
      }
    }
  }
}
</style>
