<template>
  <div class="layout-no-flex">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页
      </el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" @click="confirm" :loading="confirmLoading"><span><i
            class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div class="detail-panel form-panel">
      <el-form :model="tmpSiteStyle" ref="createSiteStyleForm" label-width="100px" style="width:450px;margin:auto;">
        <el-form-item label="名称：" prop="name" :verify="['NotNull','Length>0','Length<50']">
          <el-input style="width:197px;" v-model="tmpSiteStyle.name" @blur="getSiteStyleAlias"></el-input>
        </el-form-item>
        <el-form-item label="别名：" prop="code" :verify="['NotNull','Length>0','Length<50']">
          <el-input style="width:197px;" v-model="tmpSiteStyle.code"></el-input>
        </el-form-item>
        <el-form-item label="路径：" prop="path" :verify="['NotNull','Length>2','Length<100']">
          <path-picker :path.sync="tmpSiteStyle.path" select-title="样式生成路径"></path-picker>
        </el-form-item>
        <el-form-item label="状态：" prop="isUsing">
          <el-switch v-model="tmpSiteStyle.isUsing" on-color="#13ce66" off-color="#ff4949" active-value="Y"
            inactive-value="N" on-text="启用" off-text="停用"></el-switch>
        </el-form-item>
      </el-form>
    </div>

    <div class="style-detail right-detail-toolbar">
      <el-toolbar>
        <el-button :disabled="!tmpSiteStyle.ID" @click="addStyleNodeClickHandler" priv="SiteStyleManage.AddSubject">
          <i class="fa fa-plus"></i>添加风格节点</el-button>
      </el-toolbar>
      <el-list-view :data="nodeList.nodeDatas" ref="siteNodeTable" :data-read-url="getDataURL" :pageSize="10"
        :auto-get-data="false" @selection-change="onNodeSelectionChange">
        <template slot-scope="row">
          <div class="panel-card">
            <el-row> <a class="list-card-title" href="javascript:void(0)" @click.stop="editStyleNodeClickHandler(row)">{{row.name}}</a></el-row>
            <el-row class="list-card-buttons">
              <el-col :span="8"><span>开始时间：</span> <em>{{row.startTime | fixDateTime}}</em> </el-col>
              <el-col :span="8"><span>结束时间：</span> <em>{{row.endTime | fixDateTime}}</em> </el-col>
              <el-col :span="8" class="tar">
                <el-button @click.stop="editStyleNodeClickHandler(row)" type="text" title="编辑" priv="SiteStyleManage.EditSubject">
                  <i class="fa fa-edit"></i>编辑
                </el-button>
                <el-button @click.stop="deleteStyleNodeClickHandler([row])" type="text" title="删除" priv="SiteStyleManage.DeleteSubject">
                  <i class="fa fa-times"></i>删除
                </el-button>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-list-view>
    </div>

  </div>
</template>
<script>
import util from '@src/common/util.js'
import PathPicker from '../contentcore/components/PathPicker.vue'
export default {
  props: {
    ID: {
      type: String || Number
    }
  },
  components: {
    'path-picker': PathPicker
  },
  filters: {
    fixDateTime: function (val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      confirmLoading: false,
      tmpSiteStyle: {},
      // 风格节点列表
      nodeList: {
        selectedRows: [],
        nodeDatas: []
      },
      nodeID: 0
    }
  },
  created() {
    this.init()
  },
  methods: {
    async  init() {
      if (this.ID === 'new') {
        this.tmpSiteStyle = {
          name: '',
          code: '',
          path: 'include_style/',
          memo: '',
          isUsing: 'Y'
        }
      } else if (this.ID) {
        let res = await axios.get(`/ui/sitestyles/${this.ID}`)
        if (res.data.status === 1) {
          this.tmpSiteStyle = res.data.data
        }
        this.getStyleNodesList()
      }
      this.confirmLoading = false
    },

    // 获取站点风格结点列表
    getStyleNodesList() {
      this.$refs.siteNodeTable.getData()
    },

    addStyleNodeClickHandler() {
      this.$router.push(`${this.$route.path}/node/new`.replace(/\/\//g, '/'))
    },

    getDataURL() {
      return ['/ui/stylenodes', { params: { siteStyleID: this.ID } }]
    },

    // 风格节点单击选中行
    onNodeSelectionChange(selection) {
      this.nodeList.selectedRows = selection
    },

    // 编辑风格节点
    editStyleNodeClickHandler(row) {
      this.nodeID = row.ID
      let path = `${this.$route.path}/node/${this.nodeID}`.replace(/\/\//g, '/')
      this.$router.push(path)
    },

    // 站点风格节点：单击删除按钮
    async deleteStyleNodeClickHandler(rows) {
      if (rows.length === 0) {
        this.$alert('请先选择一条记录！', '提示', {
          type: 'info'
        })
        return
      }
      try {
        await this.$confirm('确定删除吗，删除后无法恢复。是否继续删除？', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let rowIds = []
      rows.forEach(function (row) {
        rowIds.push(row.ID)
      })
      if (!rowIds) {
        return
      }
      let strIds = rowIds.join(',')
      let res = await axios.delete(`/ui/stylenodes/${strIds}`)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.getStyleNodesList()
      }
    },

    getSiteStyleAlias() {
      if (this.tmpSiteStyle.name) {
        this.tmpSiteStyle.code = window.util.getSpell(this.tmpSiteStyle.name, true)
      }
    },

    async confirm() {
      try {
        await util.validateForm(this.$refs['createSiteStyleForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.confirmLoading = true

      let res
      if (this.ID === 'new') {
        res = await axios.post('/ui/sitestyles', this.tmpSiteStyle)
      } else {
        res = await axios.put(`/ui/sitestyles/${this.tmpSiteStyle.ID}`, this.tmpSiteStyle)
      }

      util.showResponseMessage(res.data)
      this.confirmLoading = false
      if (res.data.status === 1) {
        if (this.ID === 'new') {
          this.$router.replace(this.$route.path.replace('/new', `/${res.data.siteTyle.ID}`))
          this.tmpSiteStyle = res.data.siteTyle
        }
      }
    },

    async saveSiteStyle() {
      if (!this.tmpSiteStyle || !this.tmpSiteStyle.ID) {
        return
      }
      try {
        await util.validateForm(this.$refs['createSiteStyleForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      let data = await axios.put(`/ui/sitestyles/${this.tmpSiteStyle.ID}`, this.tmpSiteStyle)
      util.showResponseMessage(data.data)
      if (data.data.status === 1) {
        this.detailDataChange = true
      }
    }

  }
}
</script>
