<template>
  <a-card>
    <div class="cust-list-cart" ref="code">
      <a-form layout="horizontal" class="ant-advanced-search-form">
        <div>
          <a-row>
            <a-col :span="6">
              <a-form-item label="参数名称" :labelCol="{span: 8}" :wrapperCol="{span: 16}">
                <a-input @pressEnter="search" style="width: 100%" v-model="query.name" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="参数类型" :labelCol="{span: 8}" :wrapperCol="{span: 16}">
                <a-select placeholder="请选择类型" v-model="query.type" :allowClear="true" @change="search">
                  <a-select-option v-for="type in types" v-bind:value="type.valueInt" v-bind:key="type.id">
                    {{ type.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>

      <a-table
        size="middle"
        @change="sortChange"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :rowKey="rowKey"
        bordered
      >
        <div slot="title" slot-scope="data">
          <span class="cust-title">
            <a-icon type="hdd"/>{{listName}}{{data.none}}
          </span>
          <div class="cust-table-operator">
            <a-button-group>
              <a-button type="primary" @click="search">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-button-group>
          </div>
        </div>
        <div slot="footer" slot-scope="data">
          {{data.none}}
          <a-pagination
            @change="pageChange"
            :defaultPageSize="defaultPageSize"
            :pageSizeOptions="$pageSizeOptions"
            @showSizeChange="sizeChange"
            class="cust-pagination"
            size="small"
            :total="total"
            showSizeChanger
            showQuickJumper
            :showTotal="$showTotal"/>
        </div>
        <span slot="action" slot-scope="text, record">
          <a @click="editRow(record)">编辑</a>
        </span>
        <span slot="tags" slot-scope="text">
          <div v-for="option in types" :key="option.id">
            <span v-if="text == option.valueInt" :key="text">{{ option.name }}</span>
          </div>
        </span>
        <template slot="value" slot-scope="text, record">
          <span>{{ getValue(record)}}</span>
        </template>
      </a-table>
      <a-drawer
        title="系统参数编辑"
        placement="right"
        :closable="false"
        @close="onClose"
        :visible="visible"
        :width="drWidth"
        wrapClassName="sys-param"
      >
        <div>
          <a-row>
            <a-col v-if="this.showType(this.richText)" :span="24" >
              <a-form-item :label='drTitle' v-bind="formItemLayout">
                <div class="editor">
                  <tinymce-editor v-if="showEditor" ref="te" v-model="valueLongtext">
                  </tinymce-editor>
                </div>
              </a-form-item>
            </a-col>
            <a-col v-if="this.showType(this.intValue)" :span="24" >
              <a-form-item :label='drTitle' v-bind="formItemLayout">
                <div class="pub-code-value" >
                  <a-input-number style="width: 100%" v-model="valueInt"/>
                </div>
              </a-form-item>
            </a-col>
            <a-col v-if="this.showType(this.strValue)" :span="24">
              <a-form-item :label='drTitle' v-bind="formItemLayout">
                <div class="pub-code-value">
                  <a-input style="" v-model="valueStr"/>
                </div>
              </a-form-item>
            </a-col>
            <a-col v-if="this.showType(this.imgValue)" :span="24">
              <a-form-item :label='drTitle' v-bind="formItemLayout">
                <div style="" class="pub-code-value">
                  <a-upload
                    style="width: 200px; height: 200px"
                    listType="picture-card"
                    :defaultFileList="fileList"
                    :fileList="fileList"
                    :action="getUploadImageUrl(business)"
                    :headers="uploadImageHeader"
                    @change="handleChangeImg"
                    @preview="handlePreview"
                  >
                    <div v-if="fileList.length < 1">
                      <a-icon type="plus"/>
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage"/>
                  </a-modal>
                </div>
              </a-form-item>
            </a-col>
            <a-col v-if="this.showType(this.fileValue)" :span="24">
              <a-form-item :label='drTitle' v-bind="formItemLayout">
                <div style="" class="pub-code-value">
                  <a-upload
                    style="width: 200px; height: 200px"
                    :defaultFileList="fileList"
                    :fileList="fileList"
                    :action="getUploadAttachmentUrl(business)"
                    :headers="uploadImageHeader"
                    @change="handleChangeImg"
                    @preview="handlePreview"
                  >
                    <div v-if="fileList.length < 1">
                      <a-button>
                        <a-icon type="upload"/>
                        选择文件
                      </a-button>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage"/>
                  </a-modal>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="drawer-button">
            <a-button :style="{marginRight: '8px'}" @click="onClose">
              返回
            </a-button>
            <a-button type='primary' class="save-botton" @click="saveForm(record)" :loading="loading" >保存</a-button>
          </div>
        </div>
      </a-drawer>
    </div>
  </a-card>
</template>

<script>

  import {getPage, save} from "@/api/base/sysParam";
  import {getPageSaas, saveSaas} from "@/api/saas/sassParamTemplate";
  import {formatDate, humpToLine, setOrder} from "@/util/util";
  import {getCommonCode} from "@/api/system/sysCode";
  import TinymceEditor from '@/components/richtext/tinymce-editor'
  import {getUploadImageHeader, getUploadImageUrl, getUploadAttachmentUrl, isUpdateSuccess, getOneImageURL, isLoading} from "@/api/common/fileUpload";

  const richText = 'rich';
  const strValue = 'str';
  const intValue = 'int';
  const imgValue = 'img';
  const fileValue = 'file';

  const dataSource = [];
  const columns = [
    {title: '参数名称', dataIndex: 'name', width: 200},
    {title: '参数类型', dataIndex: 'type', width: 100, scopedSlots: {customRender: 'tags'}},
    {title: '参数值', key:'value', scopedSlots: {customRender: 'value'}},
    {title: '备注', width: 100, dataIndex: 'remark'},
    {title: '排序号', width: 83, dataIndex: 'showOrder', sorter: true},
    {title: '修改人', width: 85, dataIndex: 'username'},
    {
      title: '修改时间',
      dataIndex: 'lmDate',
      width: 140,
      sorter: true,
      customRender: (text) => formatDate(new Date(text), 'yyyy-MM-dd hh:mm')
    },
    {title: '操作', key: 'operation', width: 90, scopedSlots: {customRender: 'action'}}

  ];

  export default {
    name: "SysParamcomponent",
    components: {TinymceEditor},
    props:['type','listName'],
    data() {
      return {
        query: {
          page: 1,
          size: 10,
          name: "",
          type: "",
          sort: ""
        },
        rowKey: "id",
        total: 0,
        loading: false,
        columns: columns,
        dataSource: dataSource,
        isFirstLoad: true,
        visible: false,
        drWidth: '60%',
        drTitle: '',
        record: {},
        previewVisible: false,
        previewImage: '',
        fileList: [],
        business: 'SysParam',
        uploadImageHeader: getUploadImageHeader(),
        types: [],
        valueLongtext: '',
        valueStr: '',
        valueInt: 0,
        showEditor: false,
        richText,strValue,intValue,imgValue,fileValue,
        formItemLayout: {
          labelCol: {
            sm: {span: 4},
          },
          wrapperCol: {
            sm: {span: 19},
          },
        },
      }
    },
    methods: {
      getUploadImageUrl,
      getUploadAttachmentUrl,
      isUpdateSuccess,
      getOneImageURL,
      isLoading,
      reset() {
        this.query.page = 1;
        this.query.name = "";
        this.query.type = "";
        this.loadData();
      },
      handleChangeImg({fileList}) {
        this.isUpdateSuccess(fileList);
        this.loading = this.isLoading(fileList);
        this.fileList = fileList
      },
      handleCancel() {
        this.previewVisible = false
      },
      handlePreview(file) {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
      },
      handleChange({fileList}) {
        this.isUpdateSuccess(fileList);
        this.fileList = fileList;
      },
      showDrawer() {
        this.visible = true
      },
      onClose() {
        this.visible = false;
        this.record = {};
        this.fileList = [];
        this.valueLongtext = '';
        this.valueStr = '';
        this.valueInt = 0
      },
      loadData(size) {
        if (size && !isNaN(size)) {
          this.query.size = size
        }
        if (this.type === 'system') {
          getPage(this.query).then(response => {
            this.getDataThen(response);
          });
        } else {
          getPageSaas(this.query).then(response => {
            this.getDataThen(response);
          });
        }

      },
      getDataThen(response) {
        if (response && response.code == SYS_CONST.REQUEST.SUCCEED) {
          let respData = response.data;
          this.dataSource = respData.list;
          this.total = respData.total;
        }
      },
      search() {
        this.query.page = 1;
        this.loadData();
      },

      saveForm(record) {
        this.loading = true;
        let flag = false;
        if (record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.IMG || record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.FILE) {
          record.valueStr = getOneImageURL(this.fileList)
          flag = !record.valueStr;
        } else if (record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.INT) {
          record.valueInt = this.valueInt;
          flag = record.valueInt == null
        } else if (record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.STR) {
          record.valueStr = this.valueStr;
          flag = !record.valueStr;
        } else if (record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.RICH) {
          record.valueLongtext = this.valueLongtext;
          flag = !record.valueLongtext;
        }
        if (flag) {
          this.loading = false;
          this.$notification.error({message: '提示', description: "参数值不能为空", duration: 4,});
          return;
        }
        if (this.type === 'system') {
          save(record).then(resp => {
            this.saveThen(resp);
          });
        } else {
          saveSaas(record).then(resp => {
            this.saveThen(resp);
          });
        }
      },
      saveThen(resp) {
        this.loading = false;
        if (resp && resp.code == SYS_CONST.REQUEST.SUCCEED) {
          this.$notification.success({message: '系统提示', description: "保存成功", duration: 4,});
          this.loadData()
          this.onClose()
        }
      },

      editRow(row) {
        this.drTitle = row.name;
        this.record = row;
        // 单独赋值，避免不保存情况下修改到record的值
        this.valueLongtext = this.record.valueLongtext;
        this.valueStr = this.record.valueStr;
        this.valueInt = this.record.valueInt;
        if ((row.type == SYS_CONST.TEMPLATE_PARAM_TYPE.IMG || row.type == SYS_CONST.TEMPLATE_PARAM_TYPE.FILE) && row.valueStr) {
          let strs = row.valueStr.split('/');
          let image = {
            uid: '-1',
            name: strs[strs.length - 1],
            status: 'done',
            url: row.valueStr,
          };
          this.fileList.push(image)
        }
        this.showDrawer();
      },
      pageChange(page) {
        this.query.page = page;
        this.loadData();
      },
      sizeChange(current, size) {
        this.query.size = size;
        this.loadData();
      },
      sortChange(pagination, filters, sorter) {
        this.query.sort = humpToLine(sorter.field);
        this.query.order = setOrder(sorter.order);
        this.loadData();
      },
      getTypes() {
        getCommonCode([SYS_CONST.CODE.TEMPLATE_PARAM_TYPE]).then(response => {
          if (response && response.code == SYS_CONST.REQUEST.SUCCEED) {
            this.types = response.data[SYS_CONST.CODE.TEMPLATE_PARAM_TYPE];
          }
        })
      },
      showType(type) {
        if(type == this.richText) {
          return this.record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.RICH;
        }
        if(type == this.strValue) {
          return this.record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.STR;
        }
        if(type == this.imgValue) {
          return this.record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.IMG;
        }
        if(type == this.fileValue) {
          return this.record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.FILE;
        }
        if(type == this.intValue) {
          return this.record.type == SYS_CONST.TEMPLATE_PARAM_TYPE.INT;
        }
      },
      getValue(record) {
        if (record.type === SYS_CONST.TEMPLATE_PARAM_TYPE.RICH) {
          return '[点击编辑查看]';
        }
        if (record.type === SYS_CONST.TEMPLATE_PARAM_TYPE.STR) {
          return record.valueStr;
        }
        if (record.type === SYS_CONST.TEMPLATE_PARAM_TYPE.IMG) {
          return record.valueStr;
        }
        if (record.type === SYS_CONST.TEMPLATE_PARAM_TYPE.INT) {
          return record.valueInt;
        }
        if (record.type === SYS_CONST.TEMPLATE_PARAM_TYPE.FILE) {
          return record.valueStr;
        }
      }
    },
    computed: {
      defaultPageSize: function () {
        return this.$defaultPageSize()
      }
    },
    mounted() {
      this.getTypes();
    },
    deactivated() {
      this.showEditor = false;
    },
    activated() {
      this.showEditor = true;
      if (this.isFirstLoad == true) {
        this.loadData(this.defaultPageSize)
        this.isFirstLoad = false
      } else {
        let isModify = this.$route.query.isModify
        if (isModify == true) {
          this.loadData()
        } else if (isModify != undefined) {
          this.loadData()
        }
      }

    }
  }
</script>

<style scoped>

  .drawer-button {
    position: absolute;
    right: 0;
    top: 0;
    padding: 10px 16px;
    background: #fff;
    text-align: right;
  }

  .sys-param .ant-upload.ant-upload-select.ant-upload-select-text {
    height: 32px!important;
  }
</style>