<template>
	<zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
		<template slot-scope="{activeKey, data}">
			<template-page v-if="activeKey == 'list'" ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
			  :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters" :column-parsing="columnParsing"
			  :operation="operation()" :exportList="exportList">
			</template-page>
			<div v-if="~['detail'].indexOf(activeKey)" style="box-sizing: border-box;padding: 16px;">
				
        <el-descriptions border title="" :column="4" :colon="false" labelStyle="width: 8%" contentStyle="width: 17%">
          <el-descriptions-item label="所属商户">
            {{detailData.companyWechatName}}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            {{detailData.status | statusFilter}}
          </el-descriptions-item>
          <el-descriptions-item label="订单编号">
            {{detailData.orderId}}
          </el-descriptions-item>
          <el-descriptions-item label="订单类型">
            {{detailData.orderType | orderTypeFilter}}
          </el-descriptions-item>
          <el-descriptions-item label="发票类型">
            {{detailData.taxType | taxTypeFilter}}
          </el-descriptions-item>
          <el-descriptions-item label="发票内容">
            {{detailData.content}}
          </el-descriptions-item>
          <el-descriptions-item label="抬头类型">
            {{detailData.type | typeFilter}}
          </el-descriptions-item>
          <el-descriptions-item label="抬头名称">
            {{detailData.name}}
          </el-descriptions-item>
          <el-descriptions-item label="单位税号">
            {{detailData.taxNo}}
          </el-descriptions-item>
          <el-descriptions-item label="收票邮箱">
            {{detailData.receiverEmail}}
          </el-descriptions-item>
          <el-descriptions-item label="开票金额">
            {{detailData.amount}}
          </el-descriptions-item>
          <el-descriptions-item label="">
            
          </el-descriptions-item>
          <el-descriptions-item label="创建人">
            {{detailData.createBy}}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{detailData.createTime}}
          </el-descriptions-item>
          <el-descriptions-item label="上传人">
            {{detailData.upName}}
          </el-descriptions-item>
          <el-descriptions-item label="上传时间">
            {{detailData.upTime}}
          </el-descriptions-item>
        </el-descriptions>

        <h3>上传发票</h3>

        <el-form ref="formRef" :model="formData" :rules="formRules" label-position="left" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="发票时间" prop="taxTime">
                <el-date-picker
                  :disabled="detailData.status"
                  v-model="formData.taxTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择发票时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票代码" prop="taxNumber">
                <el-input v-model="formData.taxNumber" autocomplete="off" placeholder="请输入发票代码" :disabled="detailData.status"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票号码" prop="taxCode">
                <el-input v-model="formData.taxCode" autocomplete="off" placeholder="请输入发票号码" :disabled="detailData.status"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上传图片" prop="taxlink">
                <el-upload class="avatar-uploader imageListUpload" style="height:0" :action="baseURL + 'common/upload'" :headers="myHeaders"
                  :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload" :disabled="detailData.status">
                </el-upload>
                <div class="images">
                  <div class="item" v-if="formData.taxlink">
                    <div class="img">
                      <el-image :src="require('@/assets/common/pdf.png')" style="width: 120px; height: 120px; padding: 30px;" fit="cover" v-if="formData.taxlink.indexOf('pdf') >= 0"></el-image>
                      <el-image class="mainimg" ref="img" :src="formData.taxlink" style="width: 120px; height: 120px" fit="cover" :preview-src-list="[formData.taxlink]" v-else></el-image>
                      <div class="mask" v-if="!detailData.status">
                        <div class="row">
                          <div class="it" @click="uploadImage()"><i class="el-icon-upload2"></i></div>
                          <div class="it" @click="formData.taxlink = ''"><i class="el-icon-delete"></i></div>
                        </div>
                      </div>
                    </div>
                    <div>
                      <el-button @click="formData.taxlink.indexOf('pdf') >= 0 ? openFile() : openImage()" size="small">预览</el-button>
                      <el-button @click="downloadFile" size="small">下载</el-button>
                    </div>
                  </div>
                  <div class="item" v-else>
                    <div class="add" @click="uploadImage()">
                      <i class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="formData.remark" autocomplete="off" placeholder="请输入备注" :disabled="detailData.status"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

				<div slot="footer" class="dialog-footer">
				  <el-button size="mini" @click="data.removeTab()">取 消</el-button>
				  <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary" v-if="!detailData.status">确 定</el-button>
				</div>
			</div>
		</template>
	</zj-tab-page>
</template>

<script>
import { getToken } from '@/utils/auth'
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import { getList, pageExport, saveData, getDetail } from "@/api/invoice2";
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
  components: { TemplatePage },
  mixins: [import_mixin,operation_mixin],
  filters: {
    statusFilter(val) {
      const MAP = {
        true: '已开票',
        false: '待开票',
      }
      return MAP[val]
    },
    orderTypeFilter(val) {
      const MAP = {
        INCRE: '增值服务',
        ORDER: '商城订单',
      }
      return MAP[val]
    },
    taxTypeFilter(val) {
      const MAP = {
        true: '专票',
        false: '普票',
      }
      return MAP[val]
    },
    typeFilter(val) {
      const MAP = {
        true: '公司',
        false: '个人',
      }
      return MAP[val]
    }
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ["新增", "编辑"],
      formDialog: false,
      formData: {
        taxTime: '',
        taxNumber: '',
        taxCode: '',
        taxlink: '',
        remark: '',
      },
      formRules: {
        taxTime: [{ required: true, message: '请选择发票时间', trigger: 'change' }],
        taxNumber: [{ required: true, message: '请输入发票代码', trigger: 'blur' }],
        taxCode: [{ required: true, message: '请输入发票号码', trigger: 'blur' }],
        taxlink: [{ required: true, message: '请上传图片', trigger: 'change' }],
      },
			formType: 'add',
			formVisible: false,

      detailData: {},
    }
  },
  computed: {
	// 事件组合
	optionsEvensGroup() {
		return [
			[
				[
					this.optionsEvensAuth("add", {
						click: () => {
							this.openForm('add')
						}
					})
				],
			]
		]
	},
    // 更多参数
    moreParameters() {
      return []
    },
  },
  methods: {
    // 列表请求函数
    getList: getList,
    // 列表导出函数
    exportList: pageExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        detail: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openForm('detail', row.orderTaxId)
          }
        }
      })
    },
    // 打开 新增编辑 网点表单
    openForm(type, id) {
    	this.$refs.tabPage.addTab({
    		// 对应显示的模块
    		activeKey: type,
    		// 唯一标识
    		key: type,
    		// 页签名称
    		label: ({ detail: "详情" })[type],
    		// 打开时事件
    		triggerEvent: () => {
    			this.formCancel()
    			this.$nextTick(()=>{
    				this.formType = type
    				this.formVisible = true
    				if (type == 'add') {
    					this.formDialogType = 0
    				} else if(type == 'detail'){
    					this.formDialogType = 1
    					getDetail({ orderTaxId: id }).then(res => {
                this.detailData = res.data || {};
    					  this.formData.taxTime = res.data.taxTime || '';
    					  this.formData.taxNumber = res.data.taxNumber || '';
    					  this.formData.taxCode = res.data.taxCode || '';
    					  this.formData.taxlink = res.data.taxLink || '';
    					  this.formData.remark = res.data.remark || '';
    					})
    				}
    			})
    		},
    		// 关闭时事件
    		closeEvent: () => {
    		
    		}
    	})
    },

    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },

    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          saveData({...this.formData, orderTaxId: this.detailData.orderTaxId}).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            cancel('list')
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },

    uploadImage(id) {
      document.querySelector('.imageListUpload input').click();
    },

    // 附件 - 上传成功
    uploadSuccess(res, file) {
      this.formData.taxlink = res.data.url;
    },

    // 附件 - 上传前
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png', 'pdf'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传图片/pdf文件!');
        return false;
      }
    },

    openImage() {
      this.$refs.img.showViewer = true
    },

    openFile() {
      window.open(this.$xdocUrl + encodeURIComponent(Base64.encode(this.formData.taxlink)), '_blank')
    },

    downloadFile() {
      window.open(this.formData.taxlink)
    }
  }
}
</script>

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

<style scoped lang="scss">

.images {
  display: flex;
  flex-wrap: wrap;

  .item {
    display: flex;
    align-items: flex-end;

    .img {
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      overflow: hidden;
      position: relative;
      margin-right: 20px;

      .el-image {
        display: block;
      }

      .mask {
        position: absolute;
        left: 0;
        top: 0;
        width: 120px;
        height: 120px;
        background: rgba($color: #000000, $alpha: 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        opacity: 0;

        &:hover {
          opacity: 1;
        }

        .row {
          display: flex;
          align-items: center;
          justify-content: center;

          .it {
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            margin: 5px;

            i {
              font-size: 20px;
              color: #ffffff;
            }

            span {
              font-size: 14px;
              color: #ffffff;
            }
          }
        }
      }
    }

    .add {
      border: 1px dashed #eaeaea;
      border-radius: 5px;
      cursor: pointer;

      .avatar-uploader-icon {
        width: 120px;
        height: 120px;
        line-height: 120px;
      }

      &:hover {
        border: 1px dashed #66b1ff;
      }
    }
  }
}
</style>