<template>
  <div>
    <div>
      <p-card title="打印方案维护">
        <p-grid-form
          ref="formTarget"
          :items="gridItems"
          @submit="
            ($event, form) => {
              handleSubmit($event, form, 'formTarget')
            }
          "
        />
        <p-table
          v-if="tableColumnsConfig"
          ref="logTable"
          :columns="tableColumnsConfig"
          :execute="false"
          rowKey="tempid"
          :expandRowByClick="false"
          :dataSource.sync="dataSource"
          :rowSelectType="false"
          :loading="tabLoding"
          :remoteUrl="remoteUrl"
          :remoteParams="remoteParams"
          dragle
          ellipsis
          bordered
          :pagination="paginations"
        >
          <div slot="status" slot-scope="record">
            <span slot="status" v-if="record === 0">否</span>
            <span slot="status" v-if="record === 1">是</span>
          </div>
          <div slot="action" href="javascript:;" slot-scope="text">
            <a slot="action" style="margin: 0 5px" @click.stop="lookat(text)">详情</a><a-divider type="vertical" />
            <a slot="action" style="margin: 0 5px" @click.stop="edit(text)">修改</a><a-divider type="vertical" />
            <a slot="action" style="margin: 0 5px" @click.stop="deleteOne(text)">删除</a>
          </div>
        </p-table>
        <div class="btnList" slot="extra">
          <p-button type="primary" icon="plus" @click="add">新增</p-button>
        </div>
      </p-card>
    </div>
    <div>
      <p-modal
        :title="Title"
        width="850px"
        :visible="visible"
        :enlargeable="false"
        :draggable="true"
        :maskClosable="false"
        @cancel="handleCancel"
        :footer="null"
      >
        <div class="detailForm">
          <p-grid-form
            ref="formdetail"
            :items="detailFormItems"
            @submit="
              ($event, form) => {
                formSubmit($event, form, 'formdetail')
              }
            "
          >
            <div slot="" slot-scope="" class="update-btn">
              <a-upload
                :multiple="true"
                :file-list="fileList"
                @change="handleChange"
                :action="actionUrl"
                :headers="headers"
                :data="uploadData"
                :disabled="disabled"
                :showUploadList="false"
              >
                <a-button :disabled="dis">模板上传</a-button>
              </a-upload>
            </div>
          </p-grid-form>

          <div style="text-align: right">
            <p-button type="primary" v-if="isDisabled == 0 ? false : true" @click="addForm"> 保存 </p-button>
          </div>
        </div>
      </p-modal>
    </div>
  </div>
</template>
<script>
import { diffOption } from '@/views/kzyWMS/utils/index.js'
import { setFormItems, tableColumnsConfig, detailFormItems } from './js/config'
import { getList, addDetail, delDetail, updateDetail } from './api/index'
import { upcloud_base_item, upcloud_base_common, upcloud_base_chain, SERVICE_DATA_API_BASE } from "@/config/serviceSettings";
// import detailDialog from './modules/detailDialog.vue'
const initPages = (pagesSize = 10) => {
  return {
    total: 0,
    defaultCurrent: 1,
    defaultPageSize: pagesSize,
    current: 1,
    pageSize: pagesSize,
    showQuickJumper: true,
    //  size: 'small',
    showTotal: function (total, range) {
      return '从' + range[0] + '至' + range[1] + ',共' + total + '条'
    },
    showSizeChanger: true,
    pageSizeOptions: ['50', '100', '150', '200', '250', '300', '500', '1000'],
  }
}

export default {
  // components: { detailDialog },

  data() {
    return {
      remoteUrl: {
        url: `${upcloud_base_common}/printconf/list`,
        method: 'get',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        params:{}
      },
      dataSource: [],
      gridItems: setFormItems(this),
      rowSelectType: 2,
      tableColumnsConfig: null,
      detailFormItems: detailFormItems(this),
      tabLoding: false,
      Title: '',
      visible: false,
      fileList: [],
      videoUrlList: [],
      actionUrl: '/api/service-filemanagement/file/upload-file',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      uploadData: { directory: '昆中药/打印模板/', storageType: 0, isFileName: 1 },
      disabled: false,
      dis: false,
      isDisabled: null,
      paginations: initPages(50),
      remoteParams: {},
    }
  },
  mounted() {
    let warehouse = this.$store.state.user.warehouse
    this.$nextTick(() => {
      this.$refs.formTarget.form.setFieldsValue(warehouse)
      // this.getList()
    })
  },
  created() {
    diffOption(tableColumnsConfig).then((res) => {
      this.tableColumnsConfig = res
    })
    this.headers = { Authorization: 'Bearer' + JSON.parse(localStorage.getItem('token')) }
  },
  methods: {
    //弹框关闭
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.$refs.formdetail.form.resetFields()
    },
    enlargeChange(isEnlarge) {
      console.log(isEnlarge, 'isEnlarge')
    },

    //查询事件
    handleSubmit(event, form) {
      event.preventDefault()
      let bb = this.$refs.formTarget.form.getFieldsValue()
      // let aa = { pageNum: 1, pageSize: 15 }
      let params = { ...bb }
      this.tabLoding = true
      form.validateFields((error, values) => {
        if (!error) {
          this.remoteParams = params
        }
      })
    },

    //跳转新增
    add() {
      this.visible = true
      this.isDisabled = 2
      this.dis = false
      this.Title = '打印方案-新增'
      this.$nextTick(() => {
        this.$refs.formdetail.form.resetFields()
        this.$refs.formdetail.form.enableItem()
        this.$refs.formdetail.form.setFieldsValue({ printServiceUrl: 'http://127.0.0.1:6060/print' })
        this.$refs.formdetail.form.disableItem('tempname')
        this.$refs.formdetail.form.disableItem('temppath')
      })
    },

    //跳转详情
    lookat(text) {
      this.Title = `打印方案 [${text.configname}] 信息查看`
      this.isDisabled = 0
      this.dis = true
      this.visible = true
      let warehouse = this.$store.state.user.warehouse
      let test = { ...text, ...warehouse }
      this.$nextTick(() => {
        this.$refs.formdetail.form.setFieldsValue(test)
        this.$refs.formdetail.form.disableItem()
      })
    },
    //跳转修改
    edit(text) {
      this.Title = `打印方案 [${text.configname}] 信息修改`
      this.isDisabled = 1
      this.dis = false
      this.visible = true
      let warehouse = this.$store.state.user.warehouse
      let test = { ...text, ...warehouse }
      this.$nextTick(() => {
        this.$refs.formdetail.form.enableItem()
        console.log(text, '信息修改')
        this.$refs.formdetail.form.setFieldsValue(test)
      })
    },

    //保存事件
    addForm() {
      //isDisabled判断新增或修改
      if (this.isDisabled == 2) {
        const parame = this.$refs.formdetail.form.getFieldsValue()
        // let warehouse = this.$store.state.user.warehouse
        // parame.branchid = warehouse.warehouseId
        this.$refs.formdetail.form.validateFields((error, values) => {
          if (!error) {
            addDetail([parame]).then((res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.visible = false
                this.$nextTick(() => {
                  this.$refs.logTable.reload()
                  // this.getList()
                })
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      } else {
        this.$nextTick(() => {
          const parame = this.$refs.formdetail.form.getFieldsValue()
          this.$refs.formdetail.form.validateFields((error, values) => {
            if (!error) {
              updateDetail(parame).then((res) => {
                if (res.success) {
                  this.$message.success(res.message)
                  this.visible = false
                  this.$refs.logTable.reload()
                  // this.getList()
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          })
        })
      }
    },

    //删除
    deleteOne(text) {
      let _this = this
      console.log(text, 'text')
      this.$confirm({
        title: '确定是否要删除?',
        content: '',
        onOk() {
          return new Promise((resolve, reject) => {
            delDetail([text.tempid]).then((res) => {
              if (res.success) {
                _this.$message.success(res.message)
                _this.$refs.logTable.reload()
                resolve()
              } else {
                _this.$message.error(res.message)
                resolve()
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {},
      })
    },
    //upload change事件
    handleChange(info, data) {
      let { fileList } = info
      const status = info.file.status
      console.log(info, data, 'upload change事件')
      this.$refs.formdetail.form.setFieldsValue({ tempname: info.file.name })
      this.iconLoading = true
      if (status === 'done') {
        this.videoUrlList.push({ uid: fileList[fileList.length - 1].uid, url: info.file.response.message })
        this.iconLoading = false
        this.$emit('handleChange', info, data)
        if (info.file.response.success) {
          this.$message.success(info.file.response.message)
          this.$refs.formdetail.form.setFieldsValue({ temppathid: info.file.response.data.id })
          this.$refs.formdetail.form.setFieldsValue({ temppath: info.file.response.data.path })
        } else {
          this.$message.error(info.file.response.message)
        }
      }
      this.fileList = [...fileList]
    },
  },
}
</script>
<style lang="less" scoped>
.detailForm {
  position: relative;
  .update-btn {
    position: absolute;
    left: 350px;
    top: 205px;
  }
}
</style>
