<template>
  <div>
    <div class="filter-container">
      <div class="filter-control">
        <span>机构名称:</span>
        <el-input
          v-model="listQuery.authParty"
          placeholder="授权机构"
          style="width: 280px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
      </div>
    </div>
    <!-- 表格区域 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      header-row-class-name="tableHeader"
    >
      <el-table-column label="序号" :index="indexMethod" align="center" width="80" type="index" />

      <el-table-column label="机构名称" align="center" prop="authParty" />

      <el-table-column label="创建时间" class-name="status-col" width="160px">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | formatTime }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建人" class-name="status-col" width="160px" prop="createBy" /> -->
      <el-table-column label="寄送状态" width="120px" align="center">
        <template slot-scope="{ row }">
          <template v-if="row.sendStatus === 0">
            <span style="margin-right: 10px" class="status warning">待寄送</span>
          </template>
          <template v-else>
            <span style="margin-right: 10px" class="status danger">已寄送</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="navigationTo(`/logistics/club-detail?authId=${row.authId}`)">
            查看
          </el-button>
          <el-button type="primary" size="mini" @click="navigationTo(`/logistics/device-list?authId=${row.authId}`)">
            查看设备认证
          </el-button>
          <el-button v-if="sendStatus === 0" type="primary" size="mini" @click="onSend(row)"> 寄送 </el-button>
          <el-button v-else type="primary" size="mini" @click="onLookRecord(row)"> 寄送记录 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <!-- 物流信息 -->
    <el-dialog title="机构授权牌寄送" :visible.sync="dialogVisible" width="40%">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="快递公司：" prop="companyId">
          <el-select v-model="formData.companyId" placeholder="请选择快递公司" clearable>
            <template v-for="item in companyList">
              <el-option :key="item.id" :label="item.companyName" :value="item.id" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="物流编号：" prop="logisticsNumber">
          <el-input v-model="formData.logisticsNumber" placeholder="请输入物流编号" />
        </el-form-item>
        <el-form-item v-if="formData.companyId === 222" label="手机号：" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入收货人手机号" maxlength="11" show-word-limit />
        </el-form-item>
        <el-form-item label="图片备注：" prop="imageRemark">
          <el-input v-show="false" v-model="formData.imageRemark" />
          <upload-image
            tip="请上传jpg/png格式的图片，最大不超过5M，最多可上传6张"
            :multiple="true"
            :limit="6"
            accept=".jpg,.png"
            :image-list="imageRemarkList"
            :before-upload="beforeRemarkImageUpload"
            @success="uploadRemarkImageSuccess"
            @remove="handleRemarkImageRemove"
          />
        </el-form-item>
        <el-form-item label="备注：" prop="remarks">
          <el-input v-model="formData.remarks" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitLogistics">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fecthAuthList } from '@/api/auth'
import { fetchCompanyList, logisticsSend } from '@/api/logistics'
import UploadImage from '@/components/UploadImage'
import { isMobile } from '@/utils/validate'
export default {
  name: 'ComplexTable',
  components: { UploadImage },
  props: {
    sendStatus: {
      type: Number,
      default: 0
    }
  },
  data() {
    // 表单校验手机号
    const mobileValidate = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }

    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      dialogVisible: false,
      // 查询参数
      listQuery: {
        authParty: '', // 授权机构
        authUserId: '', // 供应商用户id
        pageNum: 1, // 页码
        pageSize: 10, // 分页
        status: '',
        listType: 4,
        sendStatus: ''
      },
      formData: {
        authId: '',
        companyId: '',
        logisticsNumber: '',
        imageList: '',
        remarks: '',
        imageRemark: '',
        mobile: ''
      },
      rules: {
        companyId: [{ required: true, message: '快递公司名称不能为空', trigger: ['change'] }],
        logisticsNumber: [{ required: true, message: '物流编号不能为空', trigger: ['blur'] }],
        mobile: [
          { required: true, message: '收货人手机号不能为空', trigger: ['blur'] },
          { validator: mobileValidate, trigger: ['blur'] }
        ]
      },
      companyList: [],
      imageRemarkList: []
    }
  },
  created() {
    this.listQuery.authUserId = this.$route.query.id
    this.getList()
  },
  methods: {
    // 获取授权列表
    getList() {
      this.listQuery.sendStatus = this.sendStatus
      this.listLoading = true
      fecthAuthList(this.listQuery)
        .then((response) => {
          if (response.code !== 0) {
            return this.$message.error('授权列表信息获取失败')
          }
          const { list, total } = response.data
          this.list = list
          this.total = total
        })
        .catch((err) => {
          console.log(err)
          return this.$message.error('授权列表信息获取失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },
    // 过滤列表
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    onSend(row) {
      console.log(row)
      this.fetchCompanyList()
      this.formData.authId = row.authId
      this.dialogVisible = true
    },

    onLookRecord(row) {
      console.log(row)
      this.$router.push(`/logistics/licensed-record?id=${row.authId}`)
    },

    async onSubmitLogistics() {
      try {
        await this.$refs.ruleForm.validate()
      } catch (error) {
        console.log(error)
        return
      }
      try {
        await logisticsSend(this.formData)
        this.$message.success('发货成功')
        this.dialogVisible = false
        this.getList()
      } catch (error) {
        this.$message.error('发货失败')
      }
    },

    async fetchCompanyList() {
      try {
        const res = await fetchCompanyList()
        this.companyList = res.data
      } catch (error) {
        console.log(error)
      }
    },

    uploadRemarkImageSuccess({ response, file, fileList }) {
      this.imageRemarkList = fileList
      this.formData.imageRemark = fileList.length
      this.formData.imageList = fileList.map((item) => item.response.data)
    },
    handleRemarkImageRemove({ file, fileList }) {
      this.imageRemarkList = fileList
      this.formData.imageRemark = fileList.length
      this.formData.imageList = fileList.map((item) => item.response.data)
    },
    beforeRemarkImageUpload(file) {
      const flag = file.size / 1024 / 1024 < 1
      if (!flag) {
        this.$message.error('医疗许可证图片大小不能超过 1MB!')
      }
      return flag
    },

    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style lang="scss" scoped></style>
