<template>
  <div class="app-container">
    <div v-show="viewState == 1">
      <button-bar view-title="销售政策管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="100px" class="tab-header">
              <el-form-item label="政策类别">
                <el-select v-model="listQuery.params.salesPolicyKey" placeholder="请选择" filterable>
                  <el-option v-for="item in salesPolicy_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="优惠包类别">
                <el-select v-model="listQuery.params.discountTypeKey" placeholder="请选择" filterable>
                  <el-option v-for="item in discountType_list" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否有效">
                <el-select v-model="listQuery.params.isEmploy" placeholder="请选择">
                  <el-option v-for="item in effective" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="有效期">
                <el-date-picker v-model="listQuery.params.getEffectiveStartDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
                <span style="padding: 0 8px">至</span>
                <el-date-picker v-model="listQuery.params.getEffectiveEndDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleFilter">查询</el-button>
              <el-button type="primary" size="small" icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </div>
          </div>
        </div>
        <div class="listtop">
          <div class="tit">销售政策列表</div>
          <pageye v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <div class="">
          <el-table :key="tableKey" v-loading="listLoading" :data="list" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column width="50px" type="selection" align="center"/>
            <el-table-column width="80px" label="序号" type="index" :index="indexMethod" align="center"/>
            <el-table-column width="150px" label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="primary" @click="changeNodeState(scope.row)" :disabled="scope.row.nodeState =='发起申请' ? false : scope.row.nodeState == '待提交' ? false : true">办理</el-button>
                <el-button size="small" type="primary" @click="handleCheck(scope.row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.nodeState=='待提交'" type="primary" size="mini">待提交</span>
                <span v-else @click="flowRecord(scope.row)" class="bluezi">{{ scope.row.nodeState }}</span>
              </template>
            </el-table-column>
            <el-table-column label="政策类别" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.salesPolicy }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠包类别" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.discountType }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠包名称" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.projectName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠包成本(元)" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.projectCost }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠包价值(元)" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.discountMoney }}</span>
              </template>
            </el-table-column>
            <el-table-column label="优惠项目说明" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.discountExplain }}</span>
              </template>
            </el-table-column>
            <el-table-column label="有效期" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.effectiveDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否生效" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.isEmploy == '1' ? '是' : '否' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pages">
          <div class="tit"/>
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
      </div>
    </div>
    <xiaoshouzhengce-add v-show="viewState == 2 || viewState == 3" ref="divadd" @doback="resetState" @reloadlist="getList"></xiaoshouzhengce-add>
    <xiaoshouzhengce-info v-show="viewState == 4" ref="divinfo" @doback="resetState"></xiaoshouzhengce-info>
    <el-dialog title="" :visible.sync="centerDialogVisible" width="78%" height="1%" :before-close="closeIt" center>
      <iframe frameborder="0" id="iframe" style="width:100%;" scrolling="no" :src="this.centerDialogVisible === true ? url :''"></iframe>
    </el-dialog>
  </div>
</template>

<script>
import { deleteBySids, listPage } from '@/api/jichuxinxi/salepolicy'
import { typeValues, selectHaveMessage } from '@/api/dictcommons/dictcommons'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import ButtonBar from '@/components/ButtonBar'
import xiaoshouzhengceAdd from './xiaoshouzhengceAdd'
import xiaoshouzhengceInfo from './xiaoshouzhengceInfo'
import { getStorage } from '@/utils/auth'

export default {
  name: 'xiaoshouzhengce',
  components: {
    Pagination,
    pageye,
    ButtonBar,
    xiaoshouzhengceAdd,
    xiaoshouzhengceInfo
  },
  data() {
    return {
      url: '',
      dialogHeight: '80%',
      centerDialogVisible: false,
      btndisabled: false,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'plus',
          btnKey: 'toAdd',
          btnLabel: '新增'
        },
        {
          type: 'danger',
          size: 'small',
          icon: 'del',
          btnKey: 'doDel',
          btnLabel: '删除'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      disabled: false, // 办理按钮
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      viewState: 1, // 1、列表 2、添加-车辆预订 3、编辑  4、查看 5、订金-订金收取
      // 查询 -----------
      salesPolicy_list: [], // 政策类别
      discountType_list: [], // 优惠包类别
      effective: [{ // 是否有效
        value: 1,
        label: '是'
      }, {
        value: 0,
        label: '否'
      }],
      tableKey: 0,
      list: [],
      sids: [],
      FormLoading: false,
      listLoading: false,
      listQuery: {
        current: 1,
        size: 5,
        total: 0,
        params: {
          discountTypeKey: '',	// 优惠类型key
          getEffectiveStartDate: '',	// 开始有效期
          isEmploy: '',	// 是否有效
          salesPolicyKey: '',	// 政策类别key
          staffSid: '',
          orgPath: ''
        }
      }
    }
  },
  mounted() {
    // 在外部vue的window上添加postMessage的监听，而且绑定处理函数handleMessage
    window.addEventListener('message', this.handleMessage)
    this.$refs['btnbar'].setButtonList(this.btnList)
  },
  created() {
    // 初始化变量
    this.init()
    // 加载列表
    this.getList()
  },
  methods: {
    async handleMessage(event) {
      var code = ''
      if (event.data.params !== null && event.data.params !== undefined) {
        code = event.data.params.code
      }
      if (code === 1) {
        this.init()
        this.centerDialogVisible = false
      } else if (code === 2) {
        this.dialogHeight = event.data.params.data
        this.setIframeHeight(document.getElementById('iframe'))
      }
    },
    closeIt() {
      this.url = ''
      this.centerDialogVisible = false
    },
    setIframeHeight(iframe) {
      iframe.height = this.dialogHeight
    },
    flowRecord(row) {
      this.centerDialogVisible = true
      var params = {
        deployId: row.procDefId,
        procInsId: row.procInstId,
        token: getStorage()
      }
      this.url = '/#/flow/flowRecordForBusiness?data=' + encodeURI((JSON.stringify(params)))
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    init() {
      this.getType()
    },
    // ----------功能打开开始--------
    resetState() {
      this.viewState = 1
    },
    // 重置
    handleReset() {
      this.listQuery = {
        current: 1,
        size: 5,
        total: 0,
        params: {
          discountTypeKey: '',	// 优惠类型key
          getEffectiveStartDate: '',	// 开始有效期
          isEmploy: '',	// 是否有效
          salesPolicyKey: '',	// 政策类别key
          staffSid: '',
          orgPath: ''
        }
      }
      this.getList()
    },
    // 下拉框
    getType() {
      typeValues({ type: 'discountPolicyType' }).then((res) => {
        if (res.success) {
          this.salesPolicy_list = res.data
          console.log('下拉框请求政策类别', this.salesPolicy_list)
        }
      })
      typeValues({ type: 'discountPackageType' }).then((res) => {
        if (res.success) {
          this.discountType_list = res.data
          console.log('下拉框请求优惠包类别', this.discountType_list)
        }
      })
    },
    // 打开添加
    toAdd() {
      selectHaveMessage({ menuUrl: this.$route.path, orgPath: window.sessionStorage.getItem('defaultOrgPath') }).then((resp) => {
        if (resp.success) {
          this.viewState = 2
          this.$refs['divadd'].showAdd()
        }
      })
    },
    // 打开编辑
    handleUpdate() {
      if (this.sids.length === 1) {
        this.viewState = 3
        this.$refs['divadd'].showEdit(this.sids[0])
      } else if (this.sids.length > 1) {
        this.$notify({
          title: '提示',
          message: '不能选中多个信息修改!!',
          type: 'info',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '提示',
          message: '没有选择信息!!',
          type: 'error',
          duration: 2000
        })
        return
      }
    },
    // 办理
    changeNodeState(row) {
      this.viewState = 3
      this.$refs['divadd'].showEdit(row.sid)
    },
    // 打开查看详情
    handleCheck(row) {
      this.viewState = 4
      this.$refs['divinfo'].showInfo(row.sid)
    },

    // 序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      this.listQuery.params.staffSid = window.sessionStorage.getItem('staffSid')
      this.listQuery.params.orgPath = window.sessionStorage.getItem('defaultOrgPath')
      listPage(this.listQuery).then((response) => {
        this.listLoading = false
        if (response.success) {
          this.list = response.data.records
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    // 勾选
    handleSelectionChange(row) {
      console.log('row', row)
      const aa = []
      const bb = []
      row.forEach((element) => {
        aa.push(element.sid)
        bb.push(element.depositBillTypeKey)
      })
      this.sids = aa
      this.billType = bb
      console.log('选择sid', this.sids)
      console.log('选择订单类型', this.billType)
    },
    // 根据本行ID删除数据
    doDel() {
      if (this.sids.length > 0) {
        const tip = '请确认是否删除所选记录?'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const sids = this.sids
          deleteBySids(sids).then((response) => {
            if (response.code === '200') {
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        })
      } else {
        this.$message({
          showClose: true,
          message: '请选择至少一条记录！',
          type: 'error'
        })
        return
      }
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
</style>
