<template>
    <div>
        <div class="step3-wrap min-flex">
            <div class="step3-top flex-common">
                <h3 class="flex gap8"><img src="@/assets/menu/littleTitleIcon1.svg" alt="">服务列表</h3>
                <div class="btngroup">
                    <GuipButton type="ignore" :btnstyle="{ width: '97px', height: '33px' }" @click="serviceAdd(1)">添加查重服务</GuipButton>
                    <GuipButton type="ignore" :btnstyle="{ width: '97px', height: '33px' }" @click="serviceAdd(3)">添加写作辅助</GuipButton>
                    <GuipButton type="ignore" :btnstyle="{ width: '97px', height: '33px' }" @click="serviceAdd(2)">添加AIGC</GuipButton>
                </div>
            </div>
            <div>
                <div class="flex-common table-wrap">
                    <el-form>
                        <GuipTable :border="true" :tableData="serviceList" :loading="tableLoading">
                            <el-table-column prop="name" fixed="left" label="检测服务" width="200">
                                <template slot-scope="scope">
                                    <div class="flex nowrap ">
                                        <div :class="(scope.row.type == 'a' ? 'green' : 'blue')">{{ scope.row.type == 'a' ? '查重服务' : '写作辅助'
                                            }}</div>
                                        <div class="">{{ scope.row.name }}</div>
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column prop="supply_price_desc" label="今日供货价"></el-table-column>

                            <el-table-column prop="price_desc" label="售价">
                                <template #default="{ row,$index }">
                                    <el-popover v-model="row.pricePopoverVisible" :ref="`pricePopover-${row.type}`"
                                                placement="bottom" trigger="manual" :append-to-body="false"  :visible-arrow="true"
                                                popper-class="custom-popover"  @show="popshow" >
                                        <div style="text-align: center">
                                            <div class="flex">
                                                <GuipInput ref="GuipInput" width="133px" v-model="row.price" label="售价" placeholder="请输入售价" :unit="row.price_unit"></GuipInput>
                                                <template  v-if="row.price_unit_num>1">
                                                    <span class="shortspan">/</span>
                                                    <GuipInput ref="GuipInput" width="133px" v-model="row.price_unit_num" unit="字符">
                                                    </GuipInput>
                                                </template>
                                            </div>
                                            <div class="flex" style="text-align: right; margin-top: 32px;justify-content: flex-end;">
                                                <GuipButton size="medium" @click="cancelEdit(row, 'price')">取消</GuipButton>
                                                <GuipButton type="primary" @click="saveEdit(row, 'price')" size="medium">确定</GuipButton>
                                            </div>
                                        </div>
                                        <template #reference>
                                            <div class="flex cell_render" @click="handleEditClick(row,$index,'price')">
                                                <span :key="random()">{{ row.price_desc }}</span>
                                                <svg-icon :size="16" :path="require('@/assets/site/tableEdit.svg')" :color="'#8A9099'"
                                                          :hoverColor="'#006AFF'" />
                                            </div>
                                        </template>
                                    </el-popover>
                                </template>
                            </el-table-column>


                            <el-table-column prop="sort_id" label="排序">
                                <template #default="{ row,$index }">
                                    <el-popover v-model="row.sortPopoverVisible" :ref="`popover-${row.type}`"
                                                placement="bottom" trigger="manual" :append-to-body="false"  :visible-arrow="true"
                                                popper-class="custom-popover"  @show="popshow" >
                                        <div style="text-align: center">
                                            <GuipInput ref="GuipInput" width="252px" v-model="row.edit_sort_id" label="排序" placeholder="请输入数字"></GuipInput>
                                            <p style="width: 252px;margin-left: 40px;text-align: right;color: #8A9099;letter-spacing: 0.08em;">输入＞0的数，越小排序越前；重复则新者优先；0则默认排序</p>
                                            <div class="flex" style="text-align: right; margin-top: 32px;justify-content: flex-end;">
                                                <GuipButton size="medium" @click="cancelEdit(row, 'sort')">取消</GuipButton>
                                                <GuipButton type="primary" @click="saveEdit(row, 'sort')" size="medium">确定</GuipButton>
                                            </div>
                                        </div>
                                        <template #reference>
                                            <div class="flex cell_render" @click="handleEditClick(row,$index,'sort')">
                                                <span :key="random()">{{ row.sort_id }}</span>
                                                <svg-icon :size="16" :path="require('@/assets/site/tableEdit.svg')" :color="'#8A9099'"
                                                          :hoverColor="'#006AFF'" />
                                            </div>
                                        </template>
                                    </el-popover>
                                </template>
                            </el-table-column>

                            <el-table-column prop="payment_method_desc" label="收款方式">
                                <template slot-scope="scope">
                                    <div class="flex cell_render">
                                        <span class="default-pay-method">{{scope.row.payment_method_desc}}</span>
                                        <svg-icon :size="16" :path="require('@/assets/site/tableEdit.svg')" :color="'#8A9099'" :hoverColor="'#006AFF'" />
                                    </div>
                                </template>

                                <template slot-scope="scope">
                                    <div class="flex cell_render">
                                <span :class="(scope.row.payment_method_desc == '默认站点支付' ? 'normal_payment' : 'self_payment')">
                                    {{ scope.row.payment_method_desc == '默认站点支付' ? '默认站点支付' : '自定义支付' }}
                                </span>
                                        <svg-icon :size="16" :path="require('@/assets/register/tableEdit.svg')"
                                                  @click="popPayMentModal(scope.row)" :color="'#8A9099'" :hoverColor="'#006AFF'" />
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column prop="sort_id" label="上首页">
                                <template slot-scope="scope">
                                    <div class="flex cell_render">
                                        <GuipSwitch :modelValue="scope.row.is_index_display" active-value="1" inactive-value="0" @change="onSwitchChange(scope.row)"></GuipSwitch>
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" fixed="right" min-width="150px">
                                <div class="flex">
                                    <el-button type="text">编辑</el-button>
                                    <el-button type="text">删除</el-button>
                                </div>
                            </el-table-column>
                        </GuipTable>

                        <el-pagination background @size-change='handleSizeChange' @current-change='handleCurrentChange'
                                       :current-page="currentPage" :page-size=pageSize layout="prev, pager, next,jumper"
                                       :total="serviceList.length">
                        </el-pagination>

                        <GuipDialog :dialogVisible="dialogVisible" :title="dialogTitle" :show-close-button="false" @confirm="handleConfirm"
                                    @cancel="handleCancel" type="center" >
                            <PromptText text='按住左侧图标，上下拖动可进行排序，平台卡券只能放到最后。' :type="1" class="mb24 mt12"/>
                            <PaymentMethod :paymentList="payList" @confirm="confirmPayment"/>
                        </GuipDialog>
                    </el-form>
                </div>

            </div>
        </div>

        <div class="register-btns">
            <GuipButton type="system" :btnstyle="{ width: '144px', height: '46px' }" @click="jumpStep">跳过</GuipButton>
            <GuipButton type="primary" :btnstyle="{ width: '144px', height: '46px' }" @click="nextStep">完成</GuipButton>
        </div>
    </div>
</template>
<script>

import GuipButton from "@/components/GuipButton.vue";
import GuipInput from "@/components/GuipInput.vue";
import SvgIcon from "@/components/SvgIcon.vue";
import GuipSwitch from "@/components/GuipSwitch.vue";
import GuipTable from "@/components/GuipTable.vue";
import {getServicePriceDesc} from "@/utils/common";
import PaymentMethod from "@/components/paymentMethod.vue";
import GuipDialog from "@/components/GuipDialog.vue";
import PromptText from "@/components/PromptText.vue";

export default {
  name: 'domainSet',
  props: {
     siteInfo: {
          type: Object,
          required: true
     }
  },
  components: {
      PromptText, GuipDialog, PaymentMethod,
      GuipTable, GuipSwitch, SvgIcon, GuipInput,
      GuipButton

  },
  data(){
    return {
        token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NTI2NDY1NDUsIm5iZiI6MTc1MjY0NjU0NSwiZXhwIjoxNzU1MjM4NTQ1LCJ1c2VyIjoic3VidXNlciIsImxvZ2luX3R5cGUiOjAsImFpZCI6IjEifQ.G-Is-x9qPMiV_urOlDPQVRjfAIozySxL5EK2k82d46k',
        serviceList:[],
        tableLoading:false,
        currentPage: 1,    //当前页
        pageSize: 2,   //每页的容量
        total: 0,   //列表总数
        //支付方式
        payList: [],
        //编辑图片展示
        popoverFlag:false,
        //弹框
        dialogVisible: false,   //是否展示弹框
        dialogTitle: "",    //弹框标题
        editRow:{},

        // 服务列表url
        serviceAddUrl: '/agent/siteAddFinally',
    }
  },
  mounted() {
      if(Object.keys(this.siteInfo).length === 0) {
          this.$message.error('未知错误');
          this.$emit('handelStep', 1)
          return false;
      }

      this.getSiteServiceList()
  },
  methods:{
      random() {
          return Math.random();
      },
      jumpStep(){
          this.$emit('handelStep', 4)
      },
      nextStep(){
          //保存数据

          this.$emit('handelStep', 4)
      },
      // 获取服务列表
      getSiteServiceList() {
          this.tableLoading = true
          const that = this
          that.serviceList = []
          that.$http('POST', '/agentnew/ajax_get_service_list', {
              uid: that.siteInfo.uid,
          },{
              headers:{
                  'Auth': that.token
              }
          }).then(response => {
              that.tableLoading = false
              that.$nextTick(() => {
                  that.serviceList = response.data.service_list
              })
          }).catch(error => {
              console.error(error, 'error')
          })
      },

      handleSizeChange(val) {
          this.pageSize = val
      },
      handleCurrentChange(val) {
          this.currentPage = val
      },
      serviceAdd(prodid){
          this.$router.push(this.serviceAddUrl + '?uid=' + this.siteInfo.uid + '&prodid=' + prodid)
      },

      // 点击价格单元格时触发
      handleEditClick(row, index, type) {
          // 关闭其他行的弹框
          this.popoverFlag = true;
          this.serviceList.forEach((item, i) => {
              if (i !== index) {
                  item[type + 'PopoverVisible'] = false;
              }
          });
          // 打开当前行的弹框
          row[type + 'PopoverVisible'] = true;
      },
      popshow() {
          var ariaEls = document.querySelectorAll('.el-popover')
          ariaEls.forEach((item) => {
              item.removeAttribute('aria-hidden')
          })

          ariaEls = document.querySelectorAll('.el-radio__original')
          ariaEls.forEach((item) => {
              item.removeAttribute('aria-hidden')
          })
      },
      // 保存价格
      saveEdit(row, type) {
          row[type + 'PopoverVisible'] = false; // 关闭弹框
          if(type == 'price') this.savePrice(row)
          if(type == 'sort') this.saveSort(row)
      },
      // 取消编辑
      cancelEdit(row, type) {
          row[type + 'PopoverVisible'] = false;
          this.popoverFlag = false
          // row[type + '_popover'] = false; // 关闭弹框
          // this.$Message.info('已取消编辑');
      },
      async savePrice(row){
          if (row.price === '') {
              this.$message.warning('价格不能为空');
              return;
          }

          let obj = {}
          obj.uid = this.siteInfo.uid
          obj.type = row.type
          obj.unit_num = row.price_unit_num
          if(row.price_unit == '元'){
              obj.unit_price = row.price
          }else{
              obj.unit_piece = row.price
          }

          const res = await this.saveRequest('/agentnew/ajax_set_service_price', obj)
          if(res) row.price_desc = getServicePriceDesc(row.price, row.price_unit, row.price_unit_num);
      },
      async onSwitchChange(row){
          console.log(row)
          let obj = {}
          obj.uid = this.siteInfo.uid
          obj.type = row.type
          obj.is_index_display = row.is_index_display
          const res = await this.saveRequest('/agentnew/ajax_update_service_show', obj)
          console.log(res)
          if(!res) row.is_index_display = row.is_index_display === "1" ? "0" : "1"
      },
      async saveSort(row){
          let obj = {}
          obj.uid = this.siteInfo.uid
          obj.type = row.type
          obj.sort_id = row.sort_id
          const res = await this.saveRequest('/agentnew/ajax_update_service_show', obj)
          if(res) {
              row.sort_id = row.edit_sort_id;
              this.sortServiceList()
          }
      },
      sortServiceList() {
          const sortable = this.serviceList
              .map((row, i) => ({ row, i }))
              .filter(item => item.row.sort_id > 0)
              .sort((a, b) => a.row.sort_id - b.row.sort_id);

          let i = 0;
          this.serviceList = this.serviceList.map(row => {
              if (row.sort_id > 0) {
                  return sortable[i++].row;
              }
              return row;
          });
      },
      async saveRequest(url, obj){
          const that = this
          return await this.$http('POST', url, obj,{
              headers:{
                  'Auth': this.token
              }
          }).then(response => {
              if(response.status){
                  that.$message.success('保存成功');
                  return true;
              }
              that.$message.error(response.info);
              return false;
          }).catch(error => {
              console.error(error, 'error')
          })
      },
      popPayMentModal(row){
          this.dialogVisible = true;
          this.dialogTitle = row.type_desc + '-收款方式'
          this.editRow = row
          this.getPayList(row.type)
      },
      // 获取支付列表
      getPayList(type) {
          const that = this
          that.payList = []
          this.$http('POST', '/agentnew/ajax_get_service_pay_list', {
              uid: that.siteInfo.uid,
              type: type,
          },{
              headers:{
                  'Auth': this.token
              }
          }).then(response => {
              this.$nextTick(() => {
                  that.payList = response.data.paylist
              })
          }).catch(error => {
              console.error(error, 'error')
          })
      },
      confirmPayment(payList){
          this.payList = payList
      },
      // 确认按钮事件
      async handleConfirm() {
          this.dialogVisible = false;

          let obj = {}
          obj.uid = this.siteInfo.uid
          obj.type = this.editRow.type
          obj.info = ""

          let hasClose = false
          this.payList.forEach((row) => {
              if(row.status == 1) {
                  let value = row.pay_type
                  if(row.id) value += ',' + row.id

                  obj.info = obj.info + ';' + value;
              }else{
                  hasClose = true
              }
          });
          obj.info = obj.info.substr(1, obj.info.length-1);

          await this.saveRequest('/agentnew/ajax_payment_switch', obj, this.editRow)
          const res = await this.saveRequest('/agentnew/ajax_payment_switch', obj, this.editRow)
          if(res && hasClose) {
              this.editRow.payment_method_desc = '自定义支付';
          }
      },
      // 取消按钮事件
      handleCancel() {
          this.dialogVisible = false;
      },
  }
}
</script>
<style lang="scss">
.step3-wrap {
  flex: 1;

  .step3-top {
    display: flex;
    justify-content: space-between;
    padding-bottom: 0;
    align-items: end;
    h3{
      margin: 0;
    }

    .btngroup {
      display: flex;
      height: 33px;

      button {
        font-size: 12px;
        margin-left: 12px;
      }
    }
  }
}
.custom-popover {
  position: fixed !important;
  // max-height: 290px;
  // overflow-y: auto;
  margin-top: 0 !important;
  margin-left: 0 !important;
  transform: none !important;
}
</style>