<template>
  <div>
    <el-button class="inline-24" type="primary" size="small"  @click="onShow" v-if="sys_payswitch == 1 && tool.checkAuth($route.name,'insert')" >新建付费订单</el-button>
    <el-dialog
        title="付费订单"
        :visible.sync="dialogVisible"
        width="980px"
        @close="onClose"
       >
      <el-row :gutter="20" style="margin-top: -20px">
        <el-col :span="24" v-if="payInstructions">
          <div class="pay_border">
            <span class="pay_font">付费说明：{{payInstructions}}</span>
          </div>
        </el-col>
        <el-col :span="24" class="div_top">
          <span style="color: red">*</span>
          <span>选择版本:</span>
          <el-select style="margin-left: 10px" size="small" v-model="version" placeholder="请选择" @change="onCheck">
            <el-option
                v-for="item in versionList"
                :key="item.sys_site_systempartitionid"
                :label="item.partitionname"
                :value="item.sys_site_systempartitionid">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="24" class="div_top">
          <span style="color: red">*</span>
          <span>选择付费账号:</span>
        </el-col>
        <el-col :span="24" class="div_top" v-if="sys_payincidence == '1'">
          <tableLayout ref="account1" :layout="tablecolsAccount" :data="list"  :opwidth="200" :custom="true"  :height="'240px'" fixedName="operation">
            <template v-slot:customcol="scope">
              <span v-if="scope.column.columnname === 'operation'" ></span>
              <span v-else-if="scope.column.columnname === 'enddate'">
                <span v-for="(item,index) in scope.column.data.enddate" :key="index">
                  <span v-if="form.sys_site_systempartitionid == index">{{item}}</span>
                </span>
              </span>
              <span v-else-if="scope.column.columnname === 'name'">
                <span v-if="JSON.stringify(scope.column.data.enddate) === '{}'">
                  <span style="margin-right: 10px">{{scope.column.data.name}}</span>
                  <el-tag type="danger" size="mini">未付费</el-tag>
                </span>
                <span v-else>
                  <span v-if="dataNow > JSON.stringify(scope.column.data.enddate)">
                     <span style="margin-right: 10px">{{scope.column.data.name}}</span>
                      <el-tag type="danger" size="mini">未付费</el-tag>
                  </span>
                  <span v-else>{{scope.column.data.name}}</span>
                </span>
              </span>
              <span v-else-if="scope.column.columnname === 'accountno'">
                <span v-if="scope.column.data.isleader == 1">
                  <span style="margin-right: 10px">{{scope.column.data.accountno}}</span>
                  <el-tag type="danger" size="mini">主账号</el-tag>
                </span>
                <span v-else>
                  <span>{{scope.column.data.accountno}}</span>
                </span>
              </span>
              <p v-else>{{scope.column.data[scope.column.columnname] || '--'}}</p>
            </template>
            <template v-slot:opreation="scope">
              <el-checkbox :checked="scope.data.checkRow" @change="userCheck(scope.data)" :disabled="userLeader === scope.data.userid"></el-checkbox>
            </template>
          </tableLayout>
        </el-col>
        <el-col :span="24" class="div_top" v-if="sys_payincidence == '2'">
          <tableLayout ref="account2" :layout="tablecolsMain" :data="list"  :opwidth="200" :custom="true"  :height="'370px'" fixedName="operation">
            <template v-slot:customcol="scope">
              <span v-if="scope.column.columnname === 'operation'" ></span>
              <span v-else-if="scope.column.columnname === 'enddate'">
                <span v-for="(item,index) in scope.column.data.enddate" :key="index">
                  <span v-if="form.sys_site_systempartitionid == index">{{item}}</span>
                </span>
              </span>
              <p v-else>{{scope.column.data[scope.column.columnname] || ''}}</p>
            </template>
            <template v-slot:opreation="scope">
              <el-checkbox :checked="scope.data.checkRow" @change="userCheck(scope.data)" :disabled="userLeader === scope.data.userid"></el-checkbox>
            </template>
          </tableLayout>
        </el-col>
        <el-col :span="24" class="div_top">
          <el-form :model="form"   ref="form" label-width="50px" label-position="right" size="mini">
            <el-form-item label="备注:" >
              <el-input v-model="form.remarks" placeholder="请输入备注内容"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="24" >
          <el-form :model="form"   ref="form" label-width="90px" label-position="right" size="mini" style="font-weight: bold;font-size: 15px!important;">
            <el-col :span="24"><span>使用抵扣券:</span></el-col>
            <el-row>
              <el-col :span="6" v-for="item in couponList" :key="item.index" style="margin-right: 30px">
                <div class="card" :style="{background: useColor}" v-if="item.rowindex <= usAccountNum">
                  <div class="card-left">抵扣一年</div>
                  <div class="card-right">
                    <p class="card-info">账号优惠券</p>
                    <strong class="card-time">有效期至{{item.enddate}}</strong>
                  </div>
                </div>
                <div class="card" :style="{background: bgColor}" v-else>
                  <div class="card-left">抵扣一年</div>
                  <div class="card-right">
                    <p class="card-info">账号优惠券</p>
                    <strong class="card-time">有效期至{{item.enddate}}</strong>
                  </div>
                </div>
              </el-col>
            </el-row>


<!--            <el-form-item label="使用抵扣券:" style="font-size: 20px">

            </el-form-item>-->
          </el-form>
        </el-col>
      </el-row>
      <div style="margin-top: 20px;margin-bottom: -20px">
        <el-row>
          <el-col :sapn="24">
            <div style="float: right;margin-top: 10px">
              账号数：<span style="color: red">{{accountNum}}</span>
            </div>
          </el-col>
          <el-col :sapn="24">
            <div style="float: right;margin-top: 10px">
              原价：<span style="color: red">¥{{orig_amount}}</span>
            </div>
          </el-col>
          <el-col :sapn="24">
            <div style="float: right;margin-top: 10px" v-if="coupon_amount === 0">
              优惠券抵扣：<span style="color: red">¥{{coupon_amount}}</span>
            </div>
            <div style="float: right;margin-top: 10px" v-else>
              优惠券抵扣：<span style="color: red">-¥{{tool.formatAmount(coupon_amount,2)}}</span>
            </div>
          </el-col>
          <el-col :sapn="24">
            <div style="float: right;margin-top: 10px">
              应付总额：<span style="color: red;font-size: 18px">¥{{amount}}</span>
            </div>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">
<!--        <span >共</span>
        <span style="color: red">{{accountNum}}</span>
         <span style="margin-right: 10px">个账号</span>
        <span >总价：</span>
        <span style="color: red;margin-right: 10px">¥{{amount}}</span>-->
        <el-button type="danger" @click="onSubmit" :disabled="userids.length === 0">提交订单</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableLayout from '@/components/table/index2.vue'
export default {
  name: "add",
  data() {
    return {
      // bgColor:linear-gradient(45deg, orange, red),
      bgColor:'linear-gradient(45deg, grey, grey)',
      useColor:'linear-gradient(45deg, orange, red)',
      dialogVisible:false,
      message:'',
      dataNow:'',
      versionList:[],
      modulesList:[],
      couponList:[],
      form:{
        "sys_site_systempartitionid": '',
        "orderno":'',
        "sys_payorderid": '',
        "remarks": "",
        "userids": []
      },
      tablecolsAccount:[],
      tablecolsMain:[],
      tablecolsVersion:[],
      list:[],
      param:{
        "classname": "system.payorder.payorder",
        "method": "chooseUsers",
        "content": {
          "pageNumber": 1,
          "pageSize": 999,
          "where": {
            "condition": ""
          }
        },
      },
      payInstructions:'',
      sys_payincidence:'',
      userids:[],
      accountNum:0,
      usAccountNum:0,
      amount:0,
      orig_amount:0,
      coupon_amount:0,
      createNow:false,
      sys_payswitch:'1',
      userLeader:'',
      version:"",
      isleader:''
    }
  },
  components:{tableLayout},
  methods:{
    onShow(){
      this.dialogVisible = true

      /*this.queryAccount()*/
      this.queryInstructions()
      this.queryCoupon()
      this.creatOrder()
      /*this.queryVersion()*/
    },
    /*新建订单*/
    async creatOrder(){
      const res = await this.$api.requested({
        "classname": "system.payorder.payorder",
        "method": "createOrder",
        "content": {},
      })
      this.form.sys_payorderid = res.data.sys_payorderid
      this.form.orderno = res.data.orderno
      this.queryVersion()
    },
    /*查询付费说明*/
    async queryInstructions(){
      const res = await this.$api.requested({
        "classname": "webmanage.site.site",
        "method": "querySite_Parameter",
        "content": {},
      })
      this.payInstructions = res.data.sys_payinstructions
      this.sys_payincidence = res.data.sys_payincidence
      this.sys_payswitch = res.data.sys_payswitch
    },
    /*查询可选版本信息*/
    async queryVersion(){
      const res = await this.$api.requested({
        "classname": "system.payorder.payorder",
        "method": "chooseSystemPartition",
        "content": {
          "pageNumber": 1,
          "pageSize": 999,
          "where": {
            "condition": ""
          }
        },
      })
      this.versionList = res.data.map(item=>{
        return {
          partitionname:item.partitionname,
          rowindex:item.rowindex,
          sys_site_systempartitionid:item.sys_site_systempartitionid,
          systemapp:item.systemapp,
          systemappids:item.systemappids,
          checkRow:false
        }
      })
      if (this.$route.query.isPay == 2){
        this.versionList.forEach(item=>{
          if (item.sys_site_systempartitionid == this.$route.query.id){
            this.version = item.sys_site_systempartitionid
            item.checkRow = true
            this.modulesList = item.systemapp
            this.form.sys_site_systempartitionid = item.sys_site_systempartitionid
            this.queryAccount()
            this.$refs.version.$refs.myTable.doLayout()
          }
        })
      }else {
        this.version = this.versionList[0].sys_site_systempartitionid
        this.versionList[0].checkRow = true
        this.modulesList = this.versionList[0].systemapp
        this.form.sys_site_systempartitionid = this.versionList[0].sys_site_systempartitionid
        this.queryAccount()
        this.$refs.version.$refs.myTable.doLayout()
      }

    },
    /*获取可选账号*/
    async queryAccount(){
      this.list = []
      const res = await this.$api.requested(this.param)
      this.list = res.data.map(item=>{
        return {
          accountno:item.accountno,
          name:item.name,
          agentname:item.agentname,
          enddate:item.enddate,
          isleader:item.isleader,
          phonenumber:item.phonenumber,
          rowindex:item.rowindex,
          sa_agentsid:item.sa_agentsid,
          userid:item.userid,
          checkRow:false
        }
      })
      this.isleader = 0
      this.list.forEach(item=>{
        if (item.isleader ===1){
          this.isleader = 1
          return
        }
      })
      let date = new Date()
      let dateNow = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
      this.dataNow = dateNow
      if (this.$route.query.isPay == 2){

        this.list.forEach((item,index)=>{
          for (var i=0;i<this.$route.query.userid.length;i++){
            if (item.userid == this.$route.query.userid[i]){
              item.checkRow = true
            }
          }
          if (item.isleader === 1){
            if (item.enddate[this.form.sys_site_systempartitionid]){
              if (dateNow > item.enddate[this.form.sys_site_systempartitionid]){
                item.checkRow = true
                this.userLeader = item.userid
              }
            }else {
              item.checkRow = true
              this.userLeader = item.userid
            }
          }

        })
        this.userids = []
        this.list.forEach(item=>{
          if (item.checkRow){
            this.userids.push({
              "isleader": item.isleader,
              "userid": item.userid,
              "sa_agentsid": item.sa_agentsid,
              "enddate": item.enddate[this.form.sys_site_systempartitionid]
            })
          }
        })
        this.accountNum = this.userids.length
        let newLength = this.userids.filter(item=>{
          return item.isleader !== 1
        })
        console.log(newLength,'newL')
        this.usAccountNum = newLength.length
        this.queryPrice()
        this.$refs.account1.$refs.myTable.doLayout()
        this.$refs.account2.$refs.myTable.doLayout()
      }else {
        this.list.forEach((item)=>{
          if (item.isleader === 1){
            if (item.enddate[this.form.sys_site_systempartitionid]){
              if (dateNow > item.enddate[this.form.sys_site_systempartitionid]){
                item.checkRow = true
                this.userLeader = item.userid
              }
            }else {
              item.checkRow = true
              this.userLeader = item.userid
            }
          }
        })
        this.userids = []
        this.list.forEach(item=>{
          if (item.checkRow){
            this.userids.push({
              "isleader": item.isleader,
              "userid": item.userid,
              "sa_agentsid": item.sa_agentsid,
              "enddate": item.enddate[this.form.sys_site_systempartitionid]
            })
          }
        })
        this.accountNum = this.userids.length
        let newLength = this.userids.filter(item=>{
          return item.isleader !== 1
        })
        console.log(newLength,'newL1')
        this.usAccountNum = newLength.length
        this.queryPrice()
        this.$refs.account1.$refs.myTable.doLayout()
        this.$refs.account2.$refs.myTable.doLayout()
      }

    },
    /*选择版本*/
    onCheck(val){
      this.userLeader = ''
      this.userids = []
      this.form.sys_site_systempartitionid = val
      /*this.versionList.forEach(item=>{
        if (item.sys_site_systempartitionid === val.sys_site_systempartitionid){
          item.checkRow = true
          this.form.sys_site_systempartitionid = item.sys_site_systempartitionid
        }else {
          item.checkRow = false
        }
        this.modulesList = val.systemapp
      })*/

     /* this.list.forEach(item=>{
        if (item.checkRow){
          item.checkRow = false
        }
      })
      console.log(this.list)*/
      this.queryAccount()
    },
    /*选择付费账号*/
    userCheck(val){
      this.userids = []
      if (this.userLeader !== val.userid){
        val.checkRow ? this.list[val.index].checkRow = false : this.list[val.index].checkRow = true
      }
      this.list.forEach(item=>{
        if (item.checkRow){
          this.userids.push({
            "name":item.name,
            "isleader": item.isleader,
            "userid": item.userid,
            "sa_agentsid": item.sa_agentsid,
            "enddate": item.enddate[this.form.sys_site_systempartitionid]
          })
        }
      })
      this.accountNum = this.userids.length
      this.message = ''
      this.userids.forEach((item,index)=>{
        if (item.enddate !== '' && item.enddate !== undefined){
          if (index === 0){
            this.message =  item.name
          }else {
            this.message = this.message +  '，' + item.name
          }

        }
      })
      let newLength = this.userids.filter(item=>{
        return item.isleader !== 1
      })
      this.usAccountNum = newLength.length
      this.queryPrice()
    },
    rowClick(val){
      this.onCheck(val)
    },
    onSubmit(){
      this.createNow = true
      this.queryPrice()
    },
    /*获取订单价格*/
    async queryPrice(){
      const res = await this.$api.requested({
        "classname": "system.payorder.payorder",
        "method": "insertUsers",
        "content": {
          "sys_site_systempartitionid": this.form.sys_site_systempartitionid,
          "sys_payorderid": this.form.sys_payorderid,
          "remarks": this.form.remarks,
          "users": this.userids
        },
      })
      this.amount = res.data.amount
      this.orig_amount = res.data.orig_amount
      if (this.couponList.length > 0){
        this.coupon_amount = res.data.orig_amount - res.data.amount
      }else {
        this.coupon_amount = 0
      }
      if (this.createNow){
        if (this.isleader === 1){
          if (this.message !== ''){
            this.$confirm(this.message+' 付费还未到期，是否继续付费？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if (this.amount === 0){
                this.createNow = false
                this.amount = 0
                this.orig_amount = 0
                this.coupon_amount = 0
                this.userLeader = ''
                this.form.remarks = ''
                this.accountNum = 0
                this.usAccountNum = 0
                this.isleader = 0
                this.$emit('addSuccess',this.form.orderno,this.message)
              }else {
                this.dialogVisible = false
                this.createNow = false
                this.amount = 0
                this.orig_amount = 0
                this.coupon_amount = 0
                this.userLeader = ''
                this.form.remarks = ''
                this.accountNum = 0
                this.usAccountNum = 0
                this.isleader = 0
                this.$emit('onSuccess',this.form.sys_payorderid,this.form.orderno,this.message)
              }
            }).catch(() => {

            });
          }else {
            if (this.amount === 0){
              this.createNow = false
              this.amount = 0
              this.orig_amount = 0
              this.coupon_amount = 0
              this.userLeader = ''
              this.form.remarks = ''
              this.accountNum = 0
              this.usAccountNum = 0
              this.isleader = 0
              this.$emit('addSuccess',this.form.orderno,this.message)
            }else {
              this.dialogVisible = false
              this.createNow = false
              this.amount = 0
              this.orig_amount = 0
              this.coupon_amount = 0
              this.userLeader = ''
              this.form.remarks = ''
              this.accountNum = 0
              this.usAccountNum = 0
              this.isleader = 0
              this.$emit('onSuccess',this.form.sys_payorderid,this.form.orderno,this.message)
            }
          }
        }else {
          this.$confirm('您的团队缺少主账号无法使用，请联系客服！', '提示', {
            confirmButtonText: '确定',
            showCancelButton:false,
            showClose:false,
            type: 'warning'
          }).then(() => {
            this.dialogVisible = false
            this.createNow = false
            this.amount = 0
            this.orig_amount = 0
            this.coupon_amount = 0
            this.userLeader = ''
            this.form.remarks = ''
            this.accountNum = 0
            this.usAccountNum = 0
            this.isleader = 0
          }).catch(() => {

          });
        }
      }
    },
    onClose(){
      this.dialogVisible = false
      this.createNow = false
      this.userLeader = ''
      this.form.remarks = ''
      this.amount = 0
      this.orig_amount = 0
      this.coupon_amount = 0
      this.accountNum = 0
      this.usAccountNum = 0
    },
    /*可使用优惠券*/
    async queryCoupon(){
      const res = await this.$api.requested({
        "id": 20230801162402,
        "content": {},
      })
      this.couponList = res.data
    }
  },
  created() {
    this.tablecolsAccount = this.tool.tabelCol(this.$route.name).accountTable.tablecols
    this.tablecolsMain = this.tool.tabelCol(this.$route.name).mainBodyTable.tablecols
    this.tablecolsVersion = this.tool.tabelCol(this.$route.name).versionTable.tablecols
  }
}
</script>
<style>
.card{
  display: flex;
  align-items: center;
  margin: 15px 0 10px 0;
  width: 100%;
  height: 50px;
  padding: 10px 0;
  background: #fff;
  border-radius: 8px;
  -webkit-mask-image: radial-gradient(circle at 88px 4px, transparent 4px, red 4.5px),radial-gradient(closest-side circle at 50%, red 99%, transparent 100%);
  -webkit-mask-size: 100%, 2px 4px;
  -webkit-mask-repeat: repeat, repeat-y;
  -webkit-mask-position: 0 -4px, 87px;
  -webkit-mask-composite: source-out;
  mask-composite: subtract;
  background: linear-gradient(45deg, orange, red);
}
.card-left{
  width: 88px;
  text-align: center;
  font-size: 18px;
  color: #fff;
}
.card-right{
  padding: 16px 12px;
  display: flex;
  flex: 1;
  flex-direction: column;
}
.card-info{
  margin: 0 0 10px 0;
  font-size: 14px;
  line-height: 20px;
  color:#fff;
}
.card-time{
  font-size: 12px;
  line-height: 16px;
  font-weight: normal;
  color: #fff;
  margin-top: 4px;
}
</style>
<style scoped>
 /deep/ .el-dialog__title {
   line-height: 24px;
   font-size: 16px;
   color: #303133;
   font-weight: bold;
 }
 .pay_border{
   background: #FFF9F2;
   height: 30px;
   vertical-align: center;
   line-height: 30px
 }
 .pay_font{
   color: #FA8C16;
   margin-left: 10px;
   font-size: 17px;
   font-weight: bold;
 }
 .div_top{
   margin-top: 20px;
 }

</style>
