<template>
  <ai-detail>
    <template slot="title">
      <ai-title :title="id ? '编辑项目' : '添加项目'" isShowBack isShowBottomBorder @onBackClick="cancel(false)">
      </ai-title>
    </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"
                :isShowPagination="false"
                @getList="() => {}">
              <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"
          @close="isShowLayout = false">
      </Layout>
      <ai-dv-wrapper :views="[{label: '返回'}]" @change="screenId = false" v-if="screenId" :title="form.name">
        <AppGigscreenViewer :urlPrefix="urlPrefix" :instance="instance" :dict="dict" :id="screenId"></AppGigscreenViewer>
      </ai-dv-wrapper>
      <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 AppGigscreenViewer from '../../viewer/AppGigscreenViewer'
import Layout from './Layout.vue'

export default {
  name: 'Add',

  props: {
    instance: Function,
    dict: Object,
    params: Object,
    urlPrefix: String
  },

  components: {
    Layout,
    AppGigscreenViewer
  },

  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: "请输入 大屏标题"}],
      }
    }
  },

  created() {
    this.dict.load('customizedDVs')
    if (this.params && this.params.id) {
      this.id = this.params.id
      this.getInfo(this.params.id)
    }
  },

  methods: {
    getInfo(id) {
      this.instance.post(`${this.urlPrefix}/appdiylargescreen/queryLargeScreenProjectDetailById?id=${id}`).then(res => {
        if (res.code === 0) {
          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
              }
            })
            this.total = res.data.lsList.length
          }
        }
      })
    },

    toViewer(id) {
      this.screenId = id
    },

    getList() {
      this.instance.post(`${this.urlPrefix}/appdiylargescreen/allLargeScreenByPage`, null, {
        params: {
          current: 1,
          size: 1000
        }
      }).then(res => {
        if (res.code == 0) {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },

    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
        })
      } else {
        const index = this.tableData.findIndex(v => v.id === e.id)
        this.$set(this.tableData[index], 'title', e.title)
      }
    },

    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('提交成功')
              setTimeout(() => {
                this.cancel(true)
              }, 600)
            }
          })
        }
      })
    },

    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh
      })
    },

    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>
