<template>
  <div class="settlementSet-page">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="settlementSet-baseInfo">
        <template slot="subTitle">
          <a href="javascript:;" @click="handleBack" id="settlementSet-handleBack">
            <a-icon type="left"></a-icon> 返回列表
          </a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">{{ pageInfo&&pageInfo.shelfName?pageInfo.shelfName:'--' }}</span>
        </template>
      </a-page-header>
      <a-card :bordered="false" size="small" class="settlementSet-baseInfo">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions size="small" :column="3">
              <a-descriptions-item label="配件经销商">{{ pageInfo&&pageInfo.dealerName?pageInfo.dealerName:'--' }}</a-descriptions-item>
              <a-descriptions-item label="汽车修理厂">{{ pageInfo&&pageInfo.storeName?pageInfo.storeName:'--' }}</a-descriptions-item>
              <a-descriptions-item label="货架归属">{{ pageInfo&&pageInfo.ownerType==1?'自有':'平台' }}</a-descriptions-item>
              <a-descriptions-item label="货架图片" v-if="pageInfo&&pageInfo.ownerType==1">
                <div v-if="pageInfo && pageInfo.images&&pageInfo.images.length>0">
                  <img :src="pageInfo.images[0]|| ''" width="30" height="30" class="imageUrl" @click="inited(pageInfo.images)" /> {{ '共'+pageInfo.images.length+'张' }}
                </div>
                <span v-else>--</span>
              </a-descriptions-item>
              <a-descriptions-item label="备注">{{ pageInfo&&pageInfo.remarks?pageInfo.remarks:'--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse :activeKey="['1']" class="bzj-collapse" v-if="pageInfo&&pageInfo.settleType">
          <a-collapse-panel key="1" header="保证金 ( 保证金的新增/编辑/删除请在左侧菜单“保证金管理”功能中操作 )">
            <s-table
              class="sTable fixPagination"
              ref="table"
              size="small"
              rowKey="id"
              :showPagination="false"
              :columns="columns"
              :data="loadData"
              :defaultLoadData="true"
              bordered>
              <template slot="status" slot-scope="text, record">
                <a-button type="link" @click="handleEdit(record)" id="settlementSet-handleEdit">编辑</a-button>
                <a-button type="link" @click="handleDel(record)" id="settlementSet-handleDel">删除</a-button>
              <!-- <span v-if="!($hasPermissions('B_powerMD_user_edit') && record.superAdmin!=1) && !(record.loginFlag==1 && record.ownerOrgFlag==1 && $hasPermissions('B_powerMD_user_restPwd')) && !(record.loginFlag==0 && record.ownerOrgFlag==1 && $hasPermissions('B_powerMD_user_del'))">--</span> -->
              </template>
            </s-table>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card :bordered="false" size="small" class="pages-wrap">
        <div class="settlementSet-baseInfo">
          <a-form-model
            id="settlementSet-form"
            ref="ruleForm"
            :model="form"
            :rules="rules"
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
          >
            <a-row :gutter="24">
              <a-row>
                <a-col :span="15">
                  <a-form-model-item label="结算方式" prop="settleType">
                    <v-select
                      id="settlementSet-settleType"
                      code="SHELF_SETTLE_TYPE"
                      v-model="form.settleType"
                      allowClear
                      placeholder="请选择结算方式"
                      :disabled="pageInfo&&pageInfo.settleType?true:false">
                    </v-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="1"><a-button
                  size="small"
                  type="link"
                  id="settlementSet-handleModify"
                  @click="handleModify(pageInfo,settleInfo)"
                  v-if="pageInfo&&pageInfo.settleType"
                  style="padding-top: 10px;">修改</a-button></a-col>
              </a-row>
              <a-row v-if="form.settleType=='CREDIT'">
                <a-col :span="15">
                  <a-form-model-item label="授信额度" prop="creditLimit">
                    <a-input-number
                      id="settlementSet-creditLimit"
                      v-model="form.creditLimit"
                      :precision="2"
                      :min="0.01"
                      :max="999999"
                      placeholder="请输入正数（最多允许两位小数）"
                      style="width: 100%;display: inline-block;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="1"> <span style="display: inline-block; padding: 10px;">元</span></a-col>
              </a-row>
              <a-col :span="15">
                <a-form-model-item label="结算日期" prop="settleDay" v-if="form.settleType=='MONTH'">
                  <div style="display: flex;padding: 0;align-items: center;">
                    <span style="display: inline-block;margin-right: 10px;">每月</span>
                    <a-select
                      style="background-color: none;width: 65%;"
                      placeholder="请选择结算日期"
                      id="settlementSet-settleDay"
                      allowClear
                      v-model="form.settleDay"
                    >
                      <a-select-option v-for="item in dateList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                    </a-select>
                    <span style="display: inline-block;margin-left: 10px;">号</span>
                  </div>

                </a-form-model-item>
              </a-col>
              <a-row v-if="form.settleType=='CREDIT'">
                <a-col :span="15">
                  <a-form-model-item label="结算提醒金额" prop="creditWarnLimit" >
                    <a-input-number
                      id="settlementSet-creditWarnLimit"
                      v-model="form.creditWarnLimit"
                      :precision="2"
                      :min="0.01"
                      :max="form.creditLimit-0.1"
                      placeholder="请输入正数（最多允许两位小数）"
                      style="width: 100%;display: inline-block;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="1"> <span style="display: inline-block; padding: 10px;">元</span></a-col>
              </a-row>
              <a-col :span="15">
                <a-form-model-item label="结算提醒" prop="warnBeforeDays" v-if="form.settleType=='MONTH'">
                  <div style="display: flex;padding: 0;align-items: center;">
                    <span style="display: inline-block;margin-right: 10px;">提前</span>
                    <a-select
                      style="background-color: none;width: 65%;"
                      placeholder="请选择结算提醒日期"
                      id="settlementSet-warnBeforeDays"
                      allowClear
                      v-model="form.warnBeforeDays"
                    >
                      <a-select-option v-for="item in dateTXList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                    </a-select>
                    <span style="display: inline-block;margin-left: 10px;">天开始提醒</span>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="form.settleType">
                <a-form-model-item :label="form.settleType=='CREDIT'?'超过授信额度':'超期未结算'">
                  <a-checkbox @change="onChange" id="settlementSet-settleType" :checked="form.limitFlag==1">
                    限制汽车修理厂无法使用数字货架
                  </a-checkbox>
                </a-form-model-item>
              </a-col>
              <a-col :span="15" v-if="pageInfo&&!pageInfo.settleType &&form.settleType ">
                <a-form-model-item label="是否需要缴纳保证金" prop="bondFlag" >
                  <a-radio-group name="radioGroup" v-model="form.bondFlag" @change="changeRadio" id="settlementSet-bondFlag">
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-row v-if="form.settleType&&form.bondFlag&&isEdit">
                <a-col :span="15">
                  <a-form-model-item label="保证金缴纳金额" prop="bondAmount" >
                    <a-input-number
                      id="settlementSet-bondAmount"
                      v-model="form.bondAmount"
                      :precision="2"
                      :min="0.01"
                      :max="999999"
                      placeholder="请输入正数（最多允许两位小数）"
                      style="width: 100%;display: inline-block;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="1"> <span style="display: inline-block; padding: 10px;">元</span></a-col>
              </a-row>
            </a-row>
            <a-form-model-item :label-col="{span: 0}" :wrapper-col="{span: 24}" style="text-align: center;">
              <a-button type="primary" @click="handleSubmit" id="settlementSet-handleSubmit">保存</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-card>
      <!-- 修改结算方式弹窗 -->
      <settlementModifyModal :visible="openModal" :settleInfo="settleInfo" :shelfInfo="pageInfo" @close="close"></settlementModifyModal>
    </a-spin>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import { shelfDetail, shelfSettleRuleSave, settleRuleDetail } from '@/api/shelf.js'
import { bondRecordList } from '@/api/boundRecord.js'
import settlementModifyModal from './settlementModifyModal.vue'
import { toThousands } from '@/libs/tools.js'
export default {
  components: { STable, settlementModifyModal, VSelect },
  data () {
    return {
      spinning: false,
      isEdit: false, // 货位号是否为编辑
      openModal: false, // 货位模板弹窗初始状态
      formItemLayout: {
        labelCol: { span: 13 },
        wrapperCol: { span: 11 }
      },
      settleInfo: null, // 结算详情
      // shelfInfo: null, // 数字货架详情
      settlementType: '', // 结算方式
      pageInfo: null,
      form: {
        settleType: undefined, // 结算方式
        creditLimit: '', // 授信额度
        creditWarnLimit: '', // 结算提醒金额
        settleDay: undefined, // 每月结算日
        warnBeforeDays: undefined, // 结算提醒提前天数
        limitFlag: '', // 是否限制使用
        bondFlag: '', // 是否缴纳保证金
        bondAmount: '' // 保证金金额
      },
      dateList: [{ id: 1, name: 1 }, { id: 2, name: 2 }, { id: 3, name: 3 }, { id: 4, name: 4 }, { id: 5, name: 5 }, { id: 6, name: 6 }, { id: 7, name: 7 }, { id: 8, name: 8 }, { id: 9, name: 9 }, { id: 10, name: 10 }, { id: 11, name: 11 }, { id: 12, name: 12 }, { id: 13, name: 13 }, { id: 14, name: 14 }, { id: 15, name: 15 }, { id: 16, name: 16 }, { id: 17, name: 17 }, { id: 18, name: 18 }, { id: 19, name: 19 }, { id: 20, name: 20 }, { id: 21, name: 21 }, { id: 22, name: 22 }, { id: 23, name: 23 }, { id: 24, name: 24 }, { id: 25, name: 25 }],
      dateTXList: [{ id: 1, name: 1 }, { id: 2, name: 2 }, { id: 3, name: 3 }, { id: 4, name: 4 }, { id: 5, name: 5 }, { id: 6, name: 6 }, { id: 7, name: 7 }, { id: 8, name: 8 }, { id: 9, name: 9 }, { id: 10, name: 10 }],
      rules: {
        settleType: [ { required: true, message: '请选择结算方式', trigger: 'change' } ],
        creditLimit: [ { required: true, message: '请输入授信额度', trigger: 'blur' } ],
        creditWarnLimit: [{ required: true, message: '请输入结算提醒金额', trigger: 'blur' }],
        settleDay: [ { required: true, message: '请选择每月结算日期', trigger: 'change' } ],
        warnBeforeDays: [ { required: true, message: '请选择每月结算提醒提前的日期', trigger: 'change' } ],
        bondFlag: [ { required: true, message: '请选择是否缴纳保证金', trigger: 'change' }],
        bondAmount: [ { required: true, message: '请输入保证金金额', trigger: 'blur' }]
      },
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '10%', align: 'center', customRender: function (text, record, index) { return index + 1 || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '保证金金额', dataIndex: 'bondAmount', width: '30%', align: 'right', customRender: function (text) { return toThousands(text, 2) || '--' } },
        { title: '状态', dataIndex: 'stateDictValue', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '支付时间', width: '20%', align: 'center', dataIndex: 'payDate' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return bondRecordList(Object.assign({ shelfSn: this.$route.params.shelfSn })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (let i = 0; i < data.length; i++) {
              const _item = data[i]
              _item.no = no + i + 1
            }
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    handleBack () {
      this.isEdit = false
      this.form = {}
      this.$refs.ruleForm.resetFields()
      this.$router.push({ path: '/numsGoodsShelves/goodsShelvesAdministration/list' })
      // this.$router.go(-1)
    },
    // 查看图片
    inited (viewer) {
      if (viewer) {
        const imageUrl = []
        viewer.map(item => {
          imageUrl.push(item.imageUrl)
        })
        this.$viewerApi({
          images: imageUrl
        })
      }
    },
    onChange (e) {
      console.log(e.target.checked)
      if (e.target.checked) {
        this.form.limitFlag = 1
      } else {
        this.form.limitFlag = 0
      }
    },
    //
    changeRadio (e) {
      this.isEdit = e.target.value
    },
    // 数字货架详情
    getShelfDetail () {
      this.spinning = true
      shelfDetail({
        shelfSn: this.$route.params.shelfSn
      }).then(res => {
        if (res.status == 200) {
          this.pageInfo = Object.assign({}, res.data)
          if (this.pageInfo.ownerType == 1 && this.pageInfo.images) {
            this.pageInfo.images = this.pageInfo.images.split(',')
          }
          this.settlementType = this.pageInfo.settleType
          console.log(this.form, 'this.form')
          this.$nextTick(() => {
            this.getSettleDetail()
          })
        } else {
          this.pageInfo = null
        }
        this.spinning = false
      })
    },
    // 结算详情
    getSettleDetail () {
      if (this.settlementType) {
        console.log(this.settlementType, 'this.settlementType')
        settleRuleDetail({ shelfSn: this.pageInfo.shelfSn, settleType: this.settlementType }).then(res => {
          if (res.status == 200) {
            this.form = Object.assign({}, res.data)
            this.form.limitFlag = Number(this.form.limitFlag)

            this.settleInfo = res.data
          } else {
            this.form = {}
          }
        })
      }
    },
    close (type) {
      console.log(type, 'type')
      this.settlementType = type
      this.openModal = false
      this.getSettleDetail()
      console.log(this.settlementType, 'this.settlementType')
    },
    handleEdit (row) {
      this.isEdit = true
    },
    // 修改
    handleModify (shelfVal, settleVal) {
      console.log(shelfVal, settleVal, '----------修改')
      this.pageInfo = shelfVal
      this.settleInfo = settleVal
      this.openModal = true
      console.log('----------修改')
    },
    // 保存
    handleSubmit () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = Object.assign({}, _this.form)
          console.log(params, 'params')
          if (params.limitFlag == '') {
            params.limitFlag = 0
          }
          if (this.pageInfo) {
            params.shelfSn = this.pageInfo.shelfSn
            params.storeSn = this.pageInfo.storeSn
            params.dealerSn = this.pageInfo.dealerSn
          }
          _this.spinning = true
          shelfSettleRuleSave(params).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              setTimeout(function () {
                _this.isshow = false
                _this.spinning = false
                _this.handleBack()
              }, 300)
            } else {
              _this.spinning = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    pageInit () {
      this.getShelfDetail()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
    })
  }
}
</script>

<style lang="less">
  .settlementSet-page{
    position: relative;
    height: 100%;
    padding-bottom: 51px;
    box-sizing: border-box;
    .settlementSet-baseInfo{
      margin-bottom: 10px;
      .ant-input-number-handler-wrap{
        display: none;
      }
    }
    .bzj-collapse{
      margin-top: 10px;
      .ant-collapse-content-box{
        padding: 10px !important;
      }
    }

  }
</style>
