<template>
  <div>
    <el-container>
      <!--搜索-->
      <el-header class="searchBox">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <!--          <el-form-item label="渠道编码">-->
          <!--            <el-input v-model="searchForm.channelCode" placeholder="渠道编码" />-->
          <!--          </el-form-item>-->
          <el-form-item label="key">
            <el-input v-model="searchForm.channelKey" placeholder="key" />
          </el-form-item>
          <el-form-item label="策略名称">
            <el-input v-model="searchForm.strategyName" placeholder="策略名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchBtn">查询</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-header>

<!--      <router-link tag="a" target="_blank" :to="{name:'开发测试',query:{id: 'val'}}">详情页</router-link>-->
      <!--表格-->
      <el-main class="tableBox">
        <el-button size="small" style="float: right" type="warning" icon="el-icon-circle-plus-outline" @click="add">立即创建</el-button>
        <el-table :data="tableData" stripe style="width: 100%;" default-expand-all>
          <el-table-column type="expand">
            <template slot-scope="props">
              <div style="padding: 20px">
                <div style="line-height: 40px;font-size: 16px;font-weight: bold;float: left">策略详情</div>
                <el-button size="mini" type="primary" style="float: right" @click="itemAdd(props.row)">新增</el-button>
              </div>
              <el-table border :data="props.row.strategyDetailVOList" empty-text="--" stripe style="width: 100%;">
                <el-table-column prop="strategyType" label="策略属性" width="100px">
                  <template slot-scope="ppp">
                    <div>{{ ppp.row.strategyType === 0 ? '基本策略' : '活动策略' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="primarySpid" label="主产品spid" />
                <el-table-column prop="templateName" label="使用模板" />
                <el-table-column prop="templateName" label="使用遮罩" width="100px">
                  <template slot-scope="ppp">
                    <div style="text-align: center">{{ ppp.row.remark1 === '1' ? '是' : '否' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间">
                  <template slot-scope="ppp">
                    <div style="text-align: center">{{ ppp.row.startTime ? ppp.row.startTime : '— —' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="endTime" label="结束时间">
                  <template slot-scope="ppp">
                    <div style="text-align: center">{{ ppp.row.endTime ? ppp.row.endTime : '— —' }}</div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
<!--                    <el-button type="text" size="small" @click="itemEdit(props.row, scope.row)">-->
<!--                      {{ scope.row.remark1 === "1" ? '取消遮罩' : '启用遮罩' }}-->
<!--                    </el-button>-->
                    <el-button type="text" size="small" @click="itemEdit(props.row, scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="itemDele(scope.row.id,props.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="序列号" width="65px" />
          <el-table-column prop="strategyName" label="策略名称" width="200" />
          <el-table-column prop="channelKey" label="key" />
          <el-table-column prop="fullCode" label="渠道编码" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="refresh(scope.row)">刷新</el-button>
              <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="dele(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page.sync="searchForm['pageNum']"
            :page-sizes="[20, 50, 100, 300]"
            :page-size="searchForm['pageSize']"
            layout="total, sizes, pager"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>

    <!--新增抽屉-->
    <el-drawer
      ref="addDrawer"
      title="新增策略基本信息"
      size="30%"
      :before-close="addHandleClose"
      :with-header="false"
      :visible.sync="addDialog"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <span>新增策略基本信息</span>
        <el-form :model="addForm">
          <el-form-item label="策略名称" label-width="80px">
            <el-input v-model="addForm.strategyName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="二级渠道" label-width="80px">
            <el-select v-model="addForm.channelId" filterable placeholder="请选择">
              <el-option v-for="item in channlSelect" :key="item.id" :label="item.channelName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="$refs.addDrawer.closeDrawer()">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!--编辑抽屉-->
    <el-drawer
      ref="editDrawer"
      title="编辑策略基本信息"
      size="30%"
      :before-close="editHandleClose"
      :with-header="false"
      :visible.sync="editDialog"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <span>编辑策略基本信息</span>
        <el-form :model="editForm">
          <el-form-item label="策略名称" label-width="80px">
            <el-input v-model="editForm.strategyName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="二级渠道" label-width="80px">
            <el-select v-model="editForm.channelId" filterable placeholder="请选择">
              <el-option v-for="item in channlSelect" :key="item.id" :label="item.channelName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="$refs.editDrawer.closeDrawer()">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!--详情新增抽屉-->
    <el-drawer
      ref="itemAddDrawer"
      title="新增策略详情"
      size="30%"
      :before-close="itemAddHandleClose"
      :with-header="false"
      :visible.sync="itemAddDialog"
      direction="ltr"
      custom-class="demo-drawer"
    >
      <div v-if="addDetailVO" class="demo-drawer__content">
        <span>新增策略详情</span>
        <el-form :model="addDetailVO">
          <el-form-item label="策略属性" label-width="80px">
            <el-select v-model="addDetailVO.strategyType" placeholder="请选择">
              <el-option :key="0" label="基本策略" :value="0" />
              <el-option :key="1" label="活动策略" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="主产品" label-width="80px">
            <el-select v-model="addDetailVO.primaryProductId" filterable placeholder="请选择" @change="addProChange">
              <el-option v-for="item in prodSelect" :key="item.id" :label="item.productName+' / '+item.remark+' / '+item.spid" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用模板" label-width="80px">
            <el-select v-model="addDetailVO.templateId" filterable placeholder="请选择" @change="addTplChange">
              <el-option v-for="item in modelSelect" :key="item.id" :label="item.templateName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="启用订购" label-width="80px">
            <el-switch
              v-model="addDetailVO.remark5"
              active-text="关闭"
              inactive-text="不关闭"
              active-value="1"
              inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="按钮文案" label-width="80px">
            <el-input v-model="addDetailVO.remark4" autocomplete="off" placeholder="必填"/>
          </el-form-item>
          <el-form-item label="启用遮罩" label-width="80px">
            <el-switch
              v-model="addDetailVO.remark1"
              active-text="启用"
              inactive-text="不启用"
              active-value="1"
              inactive-value="0">
            </el-switch>
          </el-form-item>
          <el-form-item label="遮罩文案" label-width="80px">
            <el-input v-model="addDetailVO.remark2" autocomplete="off" placeholder="不启用遮罩层则留空"/>
          </el-form-item>
          <el-form-item label="退订弹窗文案" label-width="80px">
            <el-input v-model="addDetailVO.remark3" autocomplete="off" placeholder="不启用则留空"/>
          </el-form-item>
          <el-form-item label="开始时间" label-width="80px">
            <div class="block">
              <el-date-picker
                v-model="addDetailVO.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="结束时间" label-width="80px">
            <div class="block">
              <el-date-picker
                v-model="addDetailVO.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              />
            </div>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="$refs.itemAddDrawer.closeDrawer()">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!--详情编辑抽屉-->
    <el-drawer
      ref="itemEditDrawer"
      title="编辑策略详情"
      size="30%"
      :before-close="cancelForm"
      :with-header="false"
      :visible.sync="itemEditDialog"
      direction="ltr"
      custom-class="demo-drawer"
    >
      <div v-if="itemEditDialog" class="demo-drawer__content">
        <span>编辑策略详情</span>
        <el-form :model="editDetailVO">
          <el-form-item label="策略属性" label-width="80px">
            <el-select v-model="editDetailVO.strategyType" placeholder="请选择">
              <el-option :key="0" label="基本策略" :value="0" />
              <el-option :key="1" label="活动策略" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="主产品" label-width="80px">
            <el-select v-model="editDetailVO.primaryProductId" filterable placeholder="请选择" @change="addProChange">
              <el-option v-for="item in prodSelect" :key="item.id" :label="item.productName+' / '+item.remark+' / '+item.spid" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用模板" label-width="80px">
            <el-select v-model="editDetailVO.templateId" filterable placeholder="请选择" @change="addTplChange">
              <el-option v-for="item in modelSelect" :key="item.id" :label="item.templateName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="关闭订购" label-width="80px">
            <el-switch
              v-model="editDetailVO.remark5"
              active-text="关闭"
              inactive-text="不关闭"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item label="按钮文案" label-width="80px">
            <el-input v-model="editDetailVO.remark4" autocomplete="off" placeholder="必填"/>
          </el-form-item>
          <el-form-item label="启用遮罩" label-width="80px">
            <el-switch
              v-model="editDetailVO.remark1"
              active-text="启用"
              inactive-text="不启用"
              active-value="1"
              inactive-value="0">
            </el-switch>
          </el-form-item>
          <el-form-item label="遮罩文案" label-width="80px">
            <el-input v-model="editDetailVO.remark2" autocomplete="off" placeholder="不启用遮罩层则留空"/>
          </el-form-item>
          <el-form-item label="退订弹窗文案" label-width="80px">
            <el-input v-model="editDetailVO.remark3" autocomplete="off" placeholder="不启用则留空"/>
          </el-form-item>
          <el-form-item label="开始时间" label-width="80px">
            <div class="block">
              <el-date-picker
                v-model="editDetailVO.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="结束时间" label-width="80px">
            <div class="block">
              <el-date-picker
                v-model="editDetailVO.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              />
            </div>
          </el-form-item>
          <el-form-item label="推荐产品" label-width="80px">
            <el-select v-model="reProdSelect" multiple filterable placeholder="请选择" @change="reProdChange">
              <el-option
                v-for="item in prodSelect"
                :key="item.id"
                :label="item.productName+' / '+item.remark"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="$refs.itemEditDrawer.closeDrawer()">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="itemEditHandleClose">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
        </div>
      </div>
    </el-drawer>
  </div>

</template>

<script>
import { post, get } from '@/api/common'
export default {
  name: 'ChannlClass',
  data() {
    return {
      loading: false,
      editDialog: false,
      addDialog: false,
      channlSelect: [],
      prodSelect: [],
      modelSelect: [],
      reProdSelect: [],
      searchForm: {
        channelKey: '',
        strategyName: '',
        pageSize: 20,
        pageNum: 1
      },
      addForm: {
        channelId: '',
        strategyName: ''
      },
      editForm: {
        channelId: '',
        strategyName: ''
      },
      tableData: [],
      total: 5000,
      itemAddDialog: false,
      addDetailVO: {
        'endTime': '',
        'primaryProductId': '',
        'primarySpid': '',
        'recommendProductVOList': [],
        'startTime': '',
        'strategyId': '',
        'strategyType': '',
        'templateId': '',
        'templateName': '',
        'remark1': '',
        'remark2': '',
        'remark3': '',
        'remark4': '',
        'remark5': ''
      },
      itemEditDialog: false,
      editDetailVO: {
        'endTime': '',
        'primaryProductId': '',
        'primarySpid': '',
        'recommendProductVOList': [],
        'startTime': '',
        'strategyId': '',
        'strategyType': '',
        'templateId': '',
        'templateName': '',
        'remark1': '',
        'remark2': '',
        'remark3': '',
        'remark4': '',
        'remark5': ''
      },
      itemIndex: 0
    }
  },
  created() {
    var that = this
    that.search()
  },
  mounted() {
    var updata = {
      pageSize: 9999,
      pageNum: 1
    }
    get('/channelInfo/listChannels', updata)
      .then((res) => {
        this.channlSelect = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    get('/productInfo/page', updata)
      .then((res) => {
        this.prodSelect = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    get('/templateInfo/page', updata)
      .then((res) => {
        this.modelSelect = res.data.list
      }).catch((err) => {
        console.log(err)
      })
  },
  methods: {
    async search() { // 同步搜索
      await get('/strategyInfo/page', this.searchForm)
        .then((res) => {
          this.tableData = res.data.list
          this.total = res.data.total
        }).catch((err) => {
          console.log(err)
        })
    },
    searchBtn() { // 搜索按钮
      this.search()
    },
    reset() { // 重置
      this.searchForm = {
        channelKey: '',
        strategyName: '',
        pageSize: 20,
        pageNum: 1
      }
      this.search()
    },
    add() { // 新增
      this.addDialog = true
    },
    addHandleClose(done) { // 新增数据
      if (this.loading) return
      this.$confirm('确定要提交吗？')
        .then(_ => {
          done()
          this.addDialog = true
          post('/strategyInfo/create', this.addForm)
            .then((res) => {
              if (res.code === 10000) this.reset()
              setTimeout(() => {
                this.addDialog = false
              }, 400)
            })
            .catch((err) => {
              console.log(err)
            })
        })
        .catch(_ => {
          this.addDialog = false
        })
    },
    edit(e) { // 编辑
      this.editForm = e
      this.editDialog = true
    },
    editHandleClose(done) { // 修改数据
      if (this.loading) return
      this.$confirm('确定要提交吗？')
        .then(_ => {
          done()
          this.editDialog = true
          this.postEdit(this.editForm)
        })
        .catch(_ => {
          this.editDialog = false
        })
    },
    refresh(row) {
      post('/strategyInfo/update/' + row.id, row)
        .then((res) => {
          this.$notify({
            title: '刷新成功',
            message: '策略名称：' + row.strategyName
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    dele(e) { // 删除
      this.$confirm('确定要删除么？')
        .then(_ => {
          post('/strategyInfo/delete', { ids: [e] })
            .then((res) => {
              if (res.code === 10000) this.reset()
            })
        })
    },
    cancelForm() { // 关闭抽屉
      this.loading = false
      this.editDialog = false
      this.addDialog = false
      this.itemEditDialog = false
      this.itemAddDialog = false
      this.reProdSelect = []
      clearTimeout(this.timer)
    },
    // 详情添加
    itemAdd(e) {
      var that = this
      this.editForm = e
      this.addDetailVO.strategyId = e.id
      that.itemAddDialog = true
    },
    itemAddHandleClose() {
      var updata = this.editForm
      updata.strategyDetailVOList = this.editForm.strategyDetailVOList ? this.editForm.strategyDetailVOList : []
      var newstrategyDetailVOList = this.makeconcat(updata.strategyDetailVOList, this.addDetailVO)
      updata.strategyDetailVOList = newstrategyDetailVOList
      this.editForm.strategyDetailVOList
      this.postEdit(updata)
    },
    itemEdit(p, e) {
      console.log(e)
      this.editForm = p
      this.editDetailVO = e
      console.log(p)
      console.log(e)
      if (!e.recommendProductVOList) {
        this.reProdSelect = []
      } else {
        for (let i = 0; i < e.recommendProductVOList.length; i++) {
          var pldata = e.recommendProductVOList[i].productId
          this.reProdSelect.push(pldata)
        }
      }

      this.itemEditDialog = true
    },
    itemEditHandleClose() {
      var updata = this.editForm
      for (let i = 0; i < updata.strategyDetailVOList.length; i++) {
        if (updata.strategyDetailVOList[i].id === this.editDetailVO.id) {
          updata.strategyDetailVOList[i] = this.editDetailVO
        }
      }
      console.log(updata)
      this.postEdit(updata)
    },
    itemDele(p, e) {
      for (let i = 0; i < e.strategyDetailVOList.length; i++) {
        if (e.strategyDetailVOList[i].id === p) {
          e.strategyDetailVOList.splice(i, 1)
        }
      }
      this.postEdit(e)
    },
    postEdit(updata) {
      post('/strategyInfo/update/' + updata.id, updata)
        .then((res) => {
          if (res.code === 10000) this.search()
          this.reProdSelect = []
          setTimeout(() => {
            this.itemEditDialog = false
            this.itemAddDialog = false
            this.editDialog = false
          }, 400)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    makeconcat(arr1, arr2) {
      return arr1.concat(arr2)
    },
    addProChange(e) {
      for (var i = 0; i < this.prodSelect.length; i++) {
        if (this.prodSelect[i].id === e) {
          this.addDetailVO.primarySpid = this.prodSelect[i].spid
        }
      }
      console.log(this.addDetailVO)
    },
    reProdChange(e) {
      this.reProdSelect = e
      var newList = []
      for (let i = 0; i < e.length; i++) {
        var list = this.editDetailVO.recommendProductVOList ? this.editDetailVO.recommendProductVOList : []
        for (let ii = 0; ii < list.length; ii++) {
          if (list[ii].id === e[i]) {
            newList = this.makeconcat(newList, list[ii])
          }
        }
        for (let iii = 0; iii < this.prodSelect.length; iii++) {
          if (this.prodSelect[iii].id === e[i]) {
            var productName = this.prodSelect[iii].productName
          }
        }
        var data = {
          productId: e[i],
          productName: productName,
          strategyDetailId: this.editDetailVO.id
        }
        newList = this.makeconcat(newList, data)
      }
      console.log(newList)
      this.editDetailVO.recommendProductVOList = newList
      console.log(this.editDetailVO)
    },
    addTplChange(e) {
      for (var i = 0; i < this.modelSelect.length; i++) {
        if (this.modelSelect[i].id === e) {
          this.addDetailVO.templateName = this.modelSelect[i].templateName
        }
      }
      console.log(this.addDetailVO)
    },
    // 分页
    handleSizeChange(e) { // 单页数量
      this.searchForm.pageSize = e
      this.search()
    },
    handleCurrentChange(e) { // 跳页
      this.searchForm.pageNum = e
      this.search()
    }
  }
}
</script>

<style scoped lang="scss">
.searchBox {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;
  height: unset !important;
  form {
    margin: auto;
    .el-form-item {
      margin: 5px 5px;
    }
  }
}
.el-header {padding: 20px}
.el-form-item {margin-bottom: unset}
.tableBox{
  margin-top: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: #bfbfbf 0 0 2px;
}
.expanded {
  background-color: #5a5e66;
}
.block {
  margin-top: 20px;
  float: right;
}
.demo-drawer__content {
  padding: 20px 5%;
  line-height: 32px;
  .el-form {
    overflow-y: scroll;
    height: 80vh;
    width: 100%;
    .el-form-item {
      margin-top: 20px;
    }
    .el-select {
      display: block;
    }
    .block[data-v-cb13e5fc] {
      margin-top: 0px;
      float: left;
    }
  }
  .demo-drawer__footer {
    position: fixed;
    bottom: 30px;
    width: 27%;
    margin-top: 20px;
    display: flex;
    button {
      flex: 1;
    }
  }

}
</style>
