<template>
  <div class="app-container container-flex">
    <!--工具栏-->
    <!-- 表单组件 -->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="700px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
        <el-col :span="14">
          <el-form-item label="文件编号" prop="code">
            <el-input v-model="form.code" size="small" class="filter-item" style="width: 280px" />
          </el-form-item>
          <el-form-item label="文件名称" prop="name">
            <el-input v-model="form.name" size="small" class="filter-item" style="width: 280px" />
          </el-form-item>
          <el-form-item label="文件描述" prop="name">
            <el-input
              v-model="form.description"
              size="small"
              class="filter-item"
              style="width: 280px"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" autosize style="width: 280px" />
          </el-form-item>
          <el-form-item label="附件" prop="attachment">
            <upload-attachment
              v-model="form.attachment"
              :loading.sync="attUploading"
              :maxSize="100 * 1024 * 1024"
              :limit="1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label-width="0px" style="margin-top: 10px">
            <upload-picture
              v-model="form.photoPath"
              :loading.sync="picUploading"
              :maxSize="5 * 1024 * 1024"
            />
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button
          :loading="crud.status.cu === 2 || picUploading || attUploading"
          type="primary"
          @click="submitRecord"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-card style="flex-grow: 1">
      <div class="head-container">
        <div v-if="crud.props.searchToggle">
          <!-- 搜索 -->
          <el-input
            v-model="qParams.code"
            clearable
            size="small"
            placeholder="输入编号搜索"
            style="width: 200px"
            class="filter-item"
          />
          <el-input
            v-model="qParams.name"
            clearable
            size="small"
            placeholder="输入名称搜索"
            style="width: 200px"
            class="filter-item"
          />
          <el-input
            v-model="qParams.description"
            clearable
            size="small"
            placeholder="输入描述搜索"
            style="width: 200px"
            class="filter-item"
          />
          <span>
            <el-button
              class="filter-item"
              size="mini"
              type="success"
              icon="el-icon-search"
              @click="toQuery"
              >搜索</el-button
            >
            <el-button
              v-if="crud.optShow.reset"
              class="filter-item"
              size="mini"
              type="warning"
              icon="el-icon-refresh-left"
              @click="crud.resetQuery()"
              >重置</el-button
            >
          </span>
        </div>
        <crudOperation :permission="permission"></crudOperation>
      </div>
      <!--表格渲染-->
      <el-table
        v-loading="crud.loading"
        :data="crud.data"
        row-key="id"
        style="width: 100%"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="item in ledgerTableOptions"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          :width="item.width"
          :align="item.align"
          :fixed="item.fixed"
          :sortable="item.sortable"
        >
        </el-table-column>
        <el-table-column label="下载链接" align="center">
          <template slot-scope="scope">
            <download-attachment :attachments="JSON.parse(scope.row.attachment)" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
            {{ scope.row.remark ? scope.row.remark : '' }}
          </template>
        </el-table-column>
        <!--   编辑与删除   -->
        <el-table-column
          v-if="checkPer(['admin', 'daohang:ledger:edit', 'daohang:ledger:del'])"
          label="操作"
          width="170px"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <div style="display: flex">
              <udOperation :data="scope.row" :permission="permission" />
              <el-button
                slot="reference"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="toDelete(scope.row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <!-- <pagination /> -->
    </el-card>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudLedger from '@/api/system/report'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import { ledgerTableOptions } from '../tableConfig'
import UploadPicture from '@/components/UploadPicture'
import UploadAttachment from '@/components/UploadAttachment'
import DownloadAttachment from '@/components/DownloadAttachment'
import CustomComponent from '@/components/CustomComponent'
import TagSelectSimple from '@/components/TagSelectSimple'
import { initData } from '@/api/data'

// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import validate from '@/utils/validate'
import dayjs from 'dayjs'

const defaultForm = {
  id: null,
  code: '',
  name: '',
  description: '',
  remark: '',
  photoPath: null,
  attachment: [],
}

export default {
  name: 'DaohangLedger',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    Treeselect,
    UploadPicture,
    UploadAttachment,
    CustomComponent,
    TagSelectSimple,
    DownloadAttachment,
  },
  cruds() {
    return CRUD({
      title: '两步路',
      url: 'report/data/getList',
      query: {
        sql: 'select * from liangbulu_file_ledger where 1=1',
      },
      listOrder: [],
      crudMethod: { ...crudLedger },
      optShow: { add: true, edit: true, del: false, reset: true, import: false, export: false },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
  },
  watch: {},
  data() {
    return {
      ledgerTableOptions,
      permission: {
        add: ['admin', 'daohang:ledger:add'],
        edit: ['admin', 'daohang:ledger:edit'],
      },
      rules: {
        code: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
      },
      fieldOptions: Array.from({ length: 50 }, (item, index) => index + 1),
      picUploading: false,
      attUploading: false,
      qParams: {
        code: null,
        name: null,
        description: null,
      },
    }
  },
  created() {},
  methods: {
    async refreshRecord(sql) {
      try {
        const res = await initData('report/data/getList', { sql: sql })
        this.crud.data = res.data.content
      } catch (err) {
        console.log(err)
      }
    },
    toQuery() {
      var str = 'select * from liangbulu_file_ledger where 1=1 '
      if (this.qParams.code && this.qParams.code !== '') {
        str = str + "and code like '%" + this.qParams.code + "%'"
      }
      if (this.qParams.name && this.qParams.name !== '') {
        str = str + "and name like '%" + this.qParams.name + "%'"
      }
      if (this.qParams.description && this.qParams.description !== '') {
        str = str + "and description like '%" + this.qParams.description + "%'"
      }
      try {
        this.refreshRecord(str)
      } catch (error) {
        console.log(err)
      }
    },
    //提交前校验
    beforeSubmit() {
      if (!this.form.name && this.form.name == '') return false
      return true
    },
    //提交数据
    async submitRecord() {
      if (this.beforeSubmit()) {
        try {
          if (this.form.id && this.form.id > 0) {
            this.obj = {
              tableName: 'liangbulu_file_ledger',
              primaryKey: 'id',
              fields: [this.form],
            }
          } else {
            this.obj = {
              tableName: 'liangbulu_file_ledger',
              fields: [
                {
                  code: this.form.code,
                  name: this.form.name,
                  description: this.form.description,
                  remark: this.form.remark,
                  attachment: this.form.attachment,
                  photoPath: this.form.photoPath,
                },
              ],
            }
          }
          const res = await initData('Report/Data/Save', this.obj)
          this.crud.cancelCU()
          // console.log(res)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.$message.error('请正确填写维修保养记录！')
      }
      this.toQuery()
    },
    //删除数据
    async doDelete(data) {
      try {
        this.obj = {
          tableName: 'liangbulu_file_ledger',
          primaryKey: 'id',
          fields: [{ id: data.id }],
        }
        const res = await initData('Report/Data/delete', this.obj)
      } catch (err) {
        console.log(err)
      }
    },
    toDelete(data) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.doDelete(data).then(() => this.toQuery())
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    [CRUD.HOOK.beforeToEdit]() {
      if (this.form.attachment) this.form.attachment = JSON.parse(this.form.attachment)
      else this.form.attachment = []
    },
    customComponentRules(item) {
      let rules = []
      if (item.isRequired)
        rules.push({
          required: item.isRequired,
          message: `${item.name}不能为空`,
          trigger: 'blur',
        })
      if (item.check)
        rules.push({
          validator: (rule, value, callback) => {
            Function(
              '"use strict"; return(function(rule, value, callback, item, validate, dayjs){' +
                item.check +
                '})'
            )()(rule, value, callback, item, validate, dayjs)
          },
          trigger: 'blur',
        })
      return rules
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.container-flex {
  display: flex;
}
</style>
