<template>
  <ai-detail>
    <template slot="title">
      <ai-title :title="id ? '编辑项目' : '添加项目'" isShowBack isShowBottomBorder @onBackClick="cancel"/>
    </template>
    <template slot="content">
      <el-form ref="form" :model="form" label-width="110px" label-position="right">
        <ai-card title="基本信息">
          <template #content>
            <div class="ai-form">
              <el-form-item label="名称" prop="name" :rules="[{ required: true, message: '请输入大屏项目名称', trigger: 'blur' }]">
                <el-input size="small" :maxlength="30" placeholder="请输入大屏项目名称" v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="描述" style="width: 100%;" prop="description">
                <el-input size="small" :maxlength="200" :rows="5" type="textarea" style="width: 100%;" placeholder="请输入描述" v-model="form.description"></el-input>
              </el-form-item>
              <el-form-item label="是否开启" style="width: 100%;" prop="status">
                <el-switch
                  v-model="form.status"
                  active-value="1"
                  inactive-value="0">
                </el-switch>
              </el-form-item>
            </div>
          </template>
        </ai-card>
        <ai-card title="大屏">
          <template #right>
            <el-button @click="add('')" type="primary">添加大屏</el-button>
            <el-button @click="dialog=true" type="primary">定制大屏</el-button>
          </template>
          <template #content>
            <ai-table
              :tableData="tableData"
              :col-configs="colConfigs"
              :total="total"
              style="margin-top: 6px;"
              :border="true"
              row-key="id"
              :isShowPagination="false"
              @getList="() => {}">
              <el-table-column slot="options" label="状态" align="center">
                <template slot-scope="{ row }">
                  <el-switch
                    v-model="row.status"
                    active-value="1"
                    @change="() => onStatusChange(row.id)">
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column slot="options" width="160px" fixed="right" label="操作" align="center">
                <template slot-scope="{ row, column, $index }">
                  <div class="table-options">
                    <el-button type="text" @click="toEdit(row.id, row.isCustom, row)">编辑</el-button>
                    <el-button type="text" @click="toViewer(row.id)">预览</el-button>
                    <el-button type="text" @click="remove($index)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </ai-table>
          </template>
        </ai-card>
      </el-form>
      <Layout
        v-if="isShowLayout"
        :instance="instance"
        :dict="dict"
        :params="query"
        @change="onChange"
        :urlPrefix="urlPrefix"
        :theme="config.theme"
        @close="isShowLayout = false">
      </Layout>
      <ai-dialog :visible.sync="dialog" title="定制大屏" @closed="custom={}" @onConfirm="handleCustomizedDV">
        <el-form ref="CustomDVFrom" size="small" :model="custom" :rules="rules" label-width="80px">
          <el-form-item label="大屏标题" prop="title">
            <el-input v-model="custom.title" clearable placeholder="请填写"/>
          </el-form-item>
          <el-form-item label="选择大屏" prop="dv">
            <ai-select v-model="custom.dv" :selectList="dict.getDict('customizedDVs')"/>
          </el-form-item>
          <el-form-item label="静态数据">
            <el-input type="textarea" rows="5" v-model="custom.meta"/>
          </el-form-item>
        </el-form>
      </ai-dialog>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">提交</el-button>
    </template>
  </ai-detail>
</template>

<script>
  import Layout from './Layout.vue'
  import Sortable from 'sortablejs'

  export default {
    name: 'Add',
    props: {
      instance: Function,
      dict: Object,
      urlPrefix: String
    },
    inject: {
      home: {default: ''}
    },
    components: {
      Layout
    },

    data() {
      return {
        info: {},
        department: [],
        form: {
          name: '',
          relationLsIds: '',
          relationLsNames: '',
          status: '1',
          description: ''
        },
        screenId: '',
        query: {},
        total: 0,
        colConfigs: [
          {prop: 'title', label: '标题'},
          {prop: 'id', label: 'ID'}
        ],
        tableData: [],
        isShowLayout: false,
        id: '',
        dialog: false,
        custom: {},
        rules: {
          dv: [{required: true, message: "请选择 定制大屏"}],
          title: [{required: true, message: "请输入 大屏标题"}],
        },
        config: {
          backgroundImage: []
        }
      }
    },

    created() {
      this.dict.load('customizedDVs')
      this.getInfo()
    },


    methods: {
      getInfo() {
        let {id} = this.$route.query
        if (!id) return
        this.instance.post(`${this.urlPrefix}/appdiylargescreen/queryLargeScreenProjectDetailById?id=${id}`).then(res => {
          if (res?.data) {
            this.form = {
              ...res.data
            }
            if (res.data.relationLsIds) {
              this.tableData = res.data.lsList.map(v => {
                let conf = JSON.parse(v.config || '') || {}
                return {
                  id: v.id,
                  title: v.title,
                  dv: conf.custom || '',
                  meta: JSON.stringify(conf.meta),
                  isCustom: !!conf.custom,
                  status: v.status
                }
              })
              this.total = res.data.lsList.length

              this.$nextTick(() => {
                this.rowDrop()
              })
            }
          }
        })
      },

      onStatusChange (id) {
        this.instance.post(`${this.urlPrefix}/appdiylargescreen/enableLargeScreen?id=${id}`).then(res => {
          if (res.code === 0) {
            this.$message.success('操作成功')
          }
        })
      },

      rowDrop() {
        const tbody = document.querySelector('.el-table__body-wrapper tbody')
        const _this = this
        Sortable.create(tbody, {
          onEnd({newIndex, oldIndex}) {
            const currRow = _this.tableData.splice(oldIndex, 1)[0]
            _this.tableData.splice(newIndex, 0, currRow)
          }
        })
      },

      toViewer(id) {
        this.$router.push({query: {id}, hash: "#preview"})
      },
      onChange(e) {
        const ids = this.tableData.map(v => v.id)
        if (ids.indexOf(e.id) < 0) {
          this.tableData.push({
            title: e.title,
            id: e.id,
            status: '1'
          })
        } else {
          const index = this.tableData.findIndex(v => v.id === e.id)
          this.$set(this.tableData[index], 'title', e.title)
        }

        this.$nextTick(() => {
          if (this.$route.query.id) {
            const ids = this.tableData.map(v => v.id).join(',')
            const names = this.tableData.map(v => v.name).join(',')
            this.instance.post(`${this.urlPrefix}/appdiylargescreen/addOrUpdateLargeScreenProject`, {
              ...this.form,
              relationLsIds: ids,
              relationLsNames: names
            }).then(res => {
              if (res.code == 0) {
              }
            })
          }
        })
      },

      add() {
        this.query = {
          id: '',
          name: this.form.name
        }
        this.isShowLayout = true
      },

      toEdit(id, isCustom, form) {
        if (!isCustom) {
          this.query = {
            id,
            name: this.form.name
          }

          this.isShowLayout = true
        } else {
          this.dialog = true
          this.custom = {
            ...form,

          }
        }
      },

      remove(index) {
        this.tableData.splice(index, 1)
      },

      confirm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const ids = this.tableData.map(v => v.id).join(',')
            const names = this.tableData.map(v => v.name).join(',')
            this.instance.post(`${this.urlPrefix}/appdiylargescreen/addOrUpdateLargeScreenProject`, {
              ...this.form,
              relationLsIds: ids,
              relationLsNames: names
            }).then(res => {
              if (res.code == 0) {
                this.$message.success('提交成功')

                this.home && this.home.refreshDvOptions && this.home.refreshDvOptions()
                setTimeout(() => {
                  this.cancel()
                }, 600)
              }
            })
          }
        })
      },

      cancel() {
        this.$router.push({})
      },

      handleCustomizedDV() {
        this.$refs.CustomDVFrom.validate(v => {
          if (v) {
            this.instance.post(`${this.urlPrefix}/appdiylargescreen/addOrUpdateLargeScreen`, {
              config: JSON.stringify({
                custom: this.custom.dv,
                meta: JSON.parse(this.custom.meta?.replace(/\\n/g, '') || null)
              }),
              status: 1,
              id: this.custom.id,
              title: this.custom.title,
            }).then(res => {
              if (res?.code == 0 && res?.data) {
                this.$message.success('保存成功')
                this.onChange(res.data)
                this.dialog = false
              }
            })
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
</style>
