
<template>
  <div>
    <el-card shadow="never" style="margin-top: 20px;">
      <template #header>
        <slot name="header">
          <vxe-toolbar ref="toolbar" :export="isHasAuth('export')" :print="isHasAuth('print')" custom>
            <template #buttons>
              <el-button
                v-if="isHasAuth('search')"
                icon="el-icon-search"
                type="primary"
                plain
                size="small"
                @click="getList"
              >搜索</el-button>
            </template>
          </vxe-toolbar>
        </slot>
      </template>

      <vxe-table
        ref="table"
        stripe
        style="margin-top: 10px"
        :loading="loading"
        :height="tableHeight"
        keep-source
        show-overflow
        :menu-config="{
          className: 'my-menus',
          body: {
            options: [
              [
                { code: 'copy', name: '复制', prefixConfig: { icon: 'vxe-icon-copy' }, suffixConfig: { content: 'Ctrl+C' } },
                { code: 'remove', name: '删除', prefixConfig: { icon: 'vxe-icon-delete-fill', className: 'color-red' } }
              ],
            ]
          }
        }"
        :row-config="{ isCurrent: true, isHover: true }"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :edit-rules="validRules"
        :edit-config="{
          trigger: 'manual',
          mode: 'row',
          showStatus: true,
          isHover: true,
          autoClear: false,
        }"
        :align="allAlign"

        :data="tableData"
        @menu-click="contextMenuClickEvent"
      >
        <vxe-column type="seq" width="58" align="center" />

        <vxe-column
          align="center"
          field="pay_status"
          width="120"
          title="订单状态"
          :formatter="({ cellValue }) => (status.get(cellValue))"
          :edit-render="{ name: 'VxeTreeSelect', options: Array.from(status), props: { multiple: false }, optionProps: { value: '0', label: '1' } }"
        />

        <vxe-column
          header-align="center"
          field="hospital.name"
          width="160"
          title="就诊医院"
        />

        <vxe-column
          header-align="center"
          field="time"
          width="180"
          title="就诊时间"
        />

        <vxe-column
          align="center"
          field="user_archive.name"
          width="160"
          title="就诊人"
        />

        <vxe-column
          align="center"
          field="my_provide"
          width="160"
          title="是否可自理"
          :formatter="({ cellValue }) => cellValue ? '是' : '否'"
        />

        <vxe-column
          align="center"
          field="appoint_mobile"
          width="160"
          title="预约人电话"
        />

        <vxe-column
          align="center"
          field="appoint_name"
          width="120"
          title="预约人"
        />

        <vxe-column
          align="center"
          field="accompany_sex"
          width="120"
          title="陪诊师性别"
          :formatter="({ cellValue }) => (new Map([[0, '任意'],[1, '男'],[2, '女']]).get(cellValue))"
        />

        <vxe-column
          field="files"
          min-width="180"
          title="上传资料"
          header-align="center"
          align="left"
        >
          <template #default="{ row }">
            <vxe-upload v-model="row['files']" name-field="original_name" readonly progress-text="{percent}%" :more-config="{ maxCount: 1, layout: 'horizontal' }" :show-button-text="false" />
          </template>
        </vxe-column>

        <vxe-column field="operate" header-align="center" title="操作" min-width="220">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button
                size="small"
                type="primary"
                @click="saveRowEvent(row)"
              >保存</el-button>
              <el-button
                size="small"
                type="primary"
                plain
                @click="cancelRowEvent(row)"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button
                v-if="isHasAuth('assign')"
                size="small"
                type="primary"
                @click="isShowAssign = true,$refs['Assign'].row = row"
              >分配</el-button>
              <el-button
                v-if="isHasAuth('detail')"
                size="small"
                type="primary"
                plain
                @click="detail(row)"
              >查看</el-button>
              <el-button
                v-if="isHasAuth('edit')"
                size="small"
                type="warning"
                @click="editRowEvent(row)"
              >编辑</el-button>
              <el-button
                v-if="isHasAuth('delete')"
                size="small"
                type="danger"
                @click="destroyRowEvent(row)"
              >删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;display: flex;justify-content: flex-end;"
        :current-page.sync="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size.sync="select.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            select.page_size = e;
            select.page = 1;
            getList();
          }
        "
        @current-change="
          (e) => {
            select.page = e;
            getList();
          }
        "
      />

    </el-card>

    <rich-text-modal ref="RichTextModal" @confirm="({ row, fieldName, text }) => row[fieldName] = text" />
    <assign ref="Assign" :nurses="nurses" :is-show.sync="isShowAssign" @refresh="getList"></assign>
  </div>
</template>

<script>
import VxeUI from 'vxe-pc-ui'
import Assign from './components/Assign.vue'
import RichTextModal from '@/components/RichTextModal/index.vue'
import { authMixin } from '@/mixin/authMixin'
import { uploadSize } from '@/settings'
import { deepCopy } from '@/utils'
import { destroy, index, save } from '@/api/accompany-order/accompany-order'
import { index as nurseIndex } from '@/api/nurse/nurse'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  name: 'AccompanyOrder',
  components: {
    Assign,
    RichTextModal
  },
  mixins: [authMixin],
  data() {
    return {
      isShowAssign: false,
      nurses: [],

      uploadSize,
      examineKey: 0,
      isShowAdd: false,
      isShowDetail: false,

      loading: false,
      tableHeight: 400,
      select: {
        page: 1,
        page_size: 20,
        keyword: '',
        show_relation: ['userArchive', 'hospital']
      },
      total: 0,
      allAlign: null,
      tableData: [],
      form: {
        id: '',
        pay_status: ''
      },
      validRules: {
        pay_status: [{ 'required': true, 'message': '标题必填' }]
      },
      status: new Map([
        [0, '待支付'],
        [1, '已支付'],
        [2, '服务中'],
        [3, '已完成']
      ])
    }
  },
  computed: {
    isActiveStatus() {
      return function(row) {
        if (this.$refs['table']) {
          return this.$refs['table'].isEditByRow(row)
        }
      }
    },
    isHasAuth() {
      return function(auth) {
        return this.auths_auth_mixin.indexOf(auth) !== -1
      }
    }
  },
  created() {
    this.getNurses()
    this.getList()
  },
  mounted() {
    this.bindToolbar()
    this.calcTableHeight()
  },
  methods: {
    calcTableHeight() {
      const clientHeight = document.documentElement.clientHeight
      const cardTitle = document.querySelector('.el-card__header')?.getBoundingClientRect()?.height
      const search = document.querySelector('.vxe-toolbar')?.getBoundingClientRect()?.height
      const paginationHeight = (document.querySelector('.el-pagination')?.getBoundingClientRect()?.height ?? 0) + 10 // 分页的高度
      const topHeight = 50 // 页面 头部
      const padding = 80
      const margin = 20
      this.tableHeight =
        clientHeight - cardTitle - search - paginationHeight - topHeight - padding - margin
    },
    contextMenuClickEvent({ menu, row, column }) {
      switch (menu.code) {
        case 'copy':
          // 示例
          if (row && column) {
            if (VxeUI.clipboard.copy(row[column.field])) {
              this.$message.success('已复制到剪贴板！')
            }
          }
          break
        case 'remove':
          if (row && column) {
            this.destroyRowEvent(row)
          }
        default:
      }
    },

    uploadMethod(file) {
      const formData = new FormData()
      formData.append('file', file)
      window.$_uploading = true
      return axios.post(process.env.VUE_APP_UPLOAD_API, formData, {
        headers: {
          Authorization: `Bearer ${getToken()}`
        }
      }).then((response) => {
        window.$_uploading = false
        if (response.status === 200 && !response.data.code) {
          return {
            response: response.data,
            name: response.data.original_name,
            url: response.data.url
          }
        } else {
          this.$message.error('上传失败')
        }
      }).catch(_ => {
        window.$_uploading = false
      })
    },
    bindToolbar() {
      this.$nextTick(() => {
        if (this.$refs['table'] && this.$refs['toolbar']) {
          this.$refs['table'].connect(this.$refs['toolbar'])
        }
      })
    },

    editRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent(row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },

    async getList() {
      this.loading = true
      try {
        const res = await index(this.select, false)
        this.tableData = res.data
        this.total = res.total
        this.loading = false
      } catch (err) {
        console.error(err)
        this.loading = false
      }
    },

    async saveRowEvent(row) {
      if (window.$_uploading) {
        this.$message.warning('文件正在上传中')
        return
      }
      try {
        const errMap = await this.$refs['table'].validate()
        if (errMap) {
          throw new Error(errMap)
        }
        await this.$confirm('确认保存？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        await this.$refs['table'].clearEdit()
        const form = deepCopy(this.form)
        for (const key in form) {
          form[key] = row[key]
        }
        this.loading = true
        await save(form, false)
        await this.getList()
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    async destroyRowEvent(row) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        })
        this.loading = true
        if (row.id) {
          await destroy({
            id: row.id
          }, false)
          await this.getList()
        } else {
          console.log(row)
          this.tableData.splice(
            this.tableData.findIndex((i) => i._X_ROW_KEY === row._X_ROW_KEY),
            1
          )
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },

    async getNurses() {
      try {
        const res = await nurseIndex({
          page: 1,
          page_size: 9999
        })
        this.nurses = res.data
      } catch (err) {
        console.error(err)
      }
    }

  }
}
</script>

<style scoped lang="scss">
::v-deep .el-card__header {
  padding: 6px 20px;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
