<template>
  <div>
    <el-form
      :model="inputQuery"
      :rules="rules"
      ref="inputQuery"
      label-width="100px"
      style="margin-top: -20px"
    >
      <el-card class="el-card">


        <div style="display: flex;">
          <el-button
            v-if="editType==2"
            type="primary"
            size="mini"
            icon="search"
            @click="onPassSubmit"
          >审核通过
          </el-button
          >
          <el-button
            v-if="editType==2"
            type="primary"
            size="mini"
            icon="search"
            @click="onRejectSubmit"
          >审核拒绝
          </el-button
          >
          <el-button
            v-if="editType==1 && auditType!=1"
            type="primary"
            size="mini"
            icon="search"
            @click="printSupCertAll"
          >打印
          </el-button>
        </div>

        <el-row :gutter="20" class="el-row" type="flex" style="margin-top: 20px">
          <el-col :span="10" class="el-col">
            <el-form-item label="所属供应商:" label-width="150px" prop="customerId">
              <el-select
                v-model="inputQuery.customerId"
                filterable
                remote
                clearable="true"
                reserve-keyword
                placeholder="请选择供应商"
                :remote-method="findMethod" disabled
                :loading="loading"
                style="width: 100%;"
                @change="supChange"
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.customerId"
                  :label="item.companyName"
                  :value="item.customerId"
                >
                  <span style="float: left">{{ item.companyName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="所属生产企业:" label-width="150px" prop="manufacturerIdFk">
              <el-select
                v-model="inputQuery.manufacturerIdFk"
                filterable
                remote
                clearable="true"
                disabled
                reserve-keyword
                placeholder="请选择生产企业"
                :remote-method="findPMMethod"
                :loading="loading"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in fromPMOptions"
                  :key="item.manufacturerId"
                  :label="item.companyName"
                  :value="item.manufacturerId"
                >
                  <span style="float: left">{{ item.companyName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="10" class="el-col">
            <el-form-item label="注册/备案号:" label-width="150px" prop="recordCode">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.recordCode" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="注册/备案产品名称:" label-width="150px" prop="recordProductName">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.recordProductName" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="10" class="el-col">
            <el-form-item label="注册/备案人名称:" label-width="150px" prop="recordPeopleName">
              <el-input
                size="small"
                placeholder="请输入内容" disabled
                v-model="inputQuery.recordPeopleName"
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="代理人名称:" label-width="150px" prop="agentName">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.agentName" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="10" class="el-col">
            <el-form-item label="医疗器械管理类别:" label-width="150px" prop="productManageType">
              <el-select
                size="small"
                v-model="inputQuery.productManageType" disabled
                placeholder="医疗器械管理类别"
                style="width: 100%;"
              >
                <el-option label="Ⅰ类" value="1"></el-option>
                <el-option label="Ⅱ类" value="2"></el-option>
                <el-option label="Ⅲ类" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="器械类别:" label-width="150px" prop="productType">
              <el-select
                size="small"
                v-model="inputQuery.productType" disabled
                placeholder="医疗器械管理类别"
                style="width: 100%;"
              >
                <el-option label="器械" value="1"></el-option>
                <el-option label="诊断试剂" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="10" class="el-col">
            <el-form-item label="器械目录分类编码:" label-width="150px" prop="productDirectoryCode">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.productDirectoryCode" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="20" class="el-col">
            <el-form-item label="规格型号:" label-width="150px" prop="specification">
              <el-input
                type="textarea"
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.specification" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="el-row" type="flex">
          <el-col :span="20" class="el-col">
            <el-form-item label="备注:" label-width="150px" prop="remark">
              <el-input
                type="textarea"
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.remark" disabled
                @input="change()"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

    </el-form>
    <el-card class="el-card">
      <el-table v-loading="certLoading" :data="certList" ref="certTable" style="width: 100%" border
                highlight-current-row>
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column label="证书名称" prop="name"></el-table-column>
        <el-table-column label="证书编号" prop="code"></el-table-column>
        <el-table-column label="生效期" prop="vailDate"></el-table-column>
        <el-table-column label="失效期" prop="expireDate"></el-table-column>
        <el-table-column label="备注" prop="remark"></el-table-column>
        <el-table-column label="证书状态" prop="status">
          <template slot-scope="scope">
            {{ supStatus[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column label="确认状态" prop="auditStatus" width="120">
          <template slot-scope="scope">
            <el-tag :type="(scope.row.auditStatus) | statusFilterType">
              {{ checkFlag[scope.row.auditStatus] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button v-if="editType==1 && auditType!=1" type="text" size="small"
                       @click.native="printSupCert(scope.row)">打印
            </el-button>
            <el-button type="text" size="small" v-if="editType==2" @click.native="auditCert(scope.row)">编辑</el-button>
            <el-button
              type="text"
              size="small"
              @click.native="showImgViewer(scope.row)"
            >预览
            </el-button>
            <el-button type="text" size="small" v-if="scope.row.auditStatus==1" @click.native="revoke(scope.row)">
              撤回
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-image-viewer
        v-if="imgViewer"
        style="z-index: 9999"
        :on-close="closeImgViewer"
        :url-list="imgList"
      />
      <el-pagination
        :page-size="certQuery.limit"
        @current-change="certHandleCurrentChange"
        layout="prev, pager, next"
        :total="certTotal"
      >
      </el-pagination>
    </el-card>

    <el-dialog width="60%" title="配送产品资质证书确认" :visible.sync="certAuditVisible" append-to-body>
      <el-form :model="currentAudit" label-width="120px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="证书名称：" prop="name">
              <el-input v-model="currentAudit.name" auto-complete="off"
                        disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="证书编号：" prop="code">
              <el-input v-model="currentAudit.code" auto-complete="off"
                        disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="生效期：" prop="vailDate">

              <el-date-picker
                v-model="currentAudit.vailDate"
                type="date"
                disabled
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择生效期">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="失效期：" prop="expireDate">

              <el-date-picker
                v-model="currentAudit.expireDate"
                type="date"
                disabled
                value-format="yyyy-MM-dd"
                style="width: 100%"
                placeholder="请选择失效期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="11">
            <el-form-item label="证书状态：" prop="status">
              <el-select v-model="currentAudit.status" :disabled="isOpen!=1" style="width: 100%">
                <el-option label="失效" :value=1></el-option>
                <el-option label="有效" :value=0></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="确认状态：" prop="confirmStatus">
              <el-select v-model="confirmStatus" :disabled="isOpen==1" style="width: 100%">
                <el-option label="符合" :value="1"></el-option>
                <el-option label="不符合" :value="2"></el-option>
                <el-option label="未确认" :value="6"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="证书文件：">
              <el-button type="primary" size="mini" @click.native="showImgViewer(currentAudit)">证书预览</el-button>
              <el-image-viewer v-if="imgViewerVisible" style="z-index:9999" :on-close="closeImgViewer"
                               :url-list="imgList"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row style="margin-top: 12px">
          <el-col :span="22">
            <el-form-item label="结果说明：">
              <el-input type="textarea" :disabled="isOpen==1" v-model="currentAudit.auditComment" autocomplete="off"
                        autosize></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确认</el-button>
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {auditSupProduct} from "../../../api/purchase/suppliersRegistrationBasic";
import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode,
} from "element-china-area-data";
import draggable from "vuedraggable";
import {
  getSupComapnys, previewImage,
  printSupCertProduction,
  verifyTemplateFile
} from '@/api/purchase/supCompany'
import {addOrModifyCompany, getCompanyList} from "@/api/purchase/supManufacturer";
import {auditSupCert, deleteCompanyCert, filterCompanyCert, revokeSupCert} from "@/api/purchase/companyCert";
import companyAddCert from "@/views/purchase/cert/supCertAddDialog";
import {getUUID} from "@/utils/strUtil";
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'


export default {
  name: "supProductEditDialog",
  props: {
    closeRegistrationDialog: {
      type: Function,
      required: true,
    },
    inputQuery: {
      type: Object,
      required: true,
    },
    editType: {
      type: Object,
      required: true,
    },
    auditType: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      fromOptions: [],
      fromPMOptions: [],
      imgViewerVisible: false,
      imgList: [],
      imgViewer: false,

      pmQuery: {
        customerId: null,
        companyName: null,
        page: 1,
        limit: 10,
      },
      loading: false,
      classesDisplay: false,
      selectedOptions: [],
      selectedOptions2: [],
      options: regionDataPlus,
      rules: {

        customerId: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "change"
          }
        ],


        manufacturerIdFk: [
          {
            required: true,
            message: "请选择生产企业",
            trigger: "change"
          }
        ],

        recordCode: [
          {
            required: true,
            message: "请输入注册/备案号",
            trigger: "blur"
          }
        ],
        recordProductName: [
          {
            required: true,
            message: "请输入注册/备案产品名称",
            trigger: "blur"
          }
        ],
        productManageType: [
          {
            required: true,
            message: "请选择医疗器械管理类别",
            trigger: "change"
          }
        ],
        productType: [
          {
            required: true,
            message: "请选择器械类别",
            trigger: "change"
          }
        ],
        recordPeopleName: [
          {
            required: true,
            message: "请输入注册/备案人名称",
            trigger: "change"
          }
        ],
        productDirectoryCode: [
          {
            required: true,
            message: "请输入器械目录分类编码",
            trigger: "change"
          }
        ],
        specification: [
          {
            required: true,
            message: "请输入规格型号",
            trigger: "change"
          }
        ],
      },
      fileList: [],
      fileList2: [],
      idQuery: {
        id: "",
      },

      certQuery: {
        customerId: null,
        manufacturerIdFk: null,
        page: 1,
        limit: 20
      },
      certList: [],
      certTotal: 0,
      certLoading: false,
      addCertVisible: false,
      certFileUrl: "",
      addType: "3", //证书类型：1:供应商；2.生产企业；3.产品品种
      checkFlag: {
        0: "草稿",
        1: "已确认",
        2: "已拒绝",
        3: "变更未确认",
        6: "未确认",
      },
      supStatus: {
        0: "有效",
        1: "失效",
      },
      confirmStatus: null,
      isOpen: false,
      certAuditVisible: false,
      currentAudit: {},
    };
  },
  created() {
    if (this.editType == 0) {
      this.inputQuery.productId = getUUID("");
    } else {
      if (this.editType != 2 && this.editType != 0) {
        this.certQuery.auditStatus = 20;
      }
      this.getCompanyCertList();
      this.pmQuery.customerId = this.inputQuery.customerId;
      this.findPMMethod();
    }

    this.findMethod();
    this.certFileUrl = this.BASE_URL + "/udiwms/image/register/file/getImage?type=image2&name=";

  },
  components: {
    draggable, companyAddCert, ElImageViewer
  },
  methods: {

    onPassSubmit() {
      this.$confirm("是否审核通过?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        this.inputQuery.auditStatus = 1;
        auditSupProduct(this.inputQuery).then(response => {
          this.loading = false;
          if (response.code === 20000) {
            this.closeRegistrationDialog(true);
            this.$message.success("保存成功");
          } else {
            this.$message.error(response.message);
          }
        });
      }).catch(() => {
      });
    },
    isAssetTypeAnImage(ext) {
      return [
        'png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
    },
    showImgViewer(row) {
      // let newWindow = window.open();
      // newWindow.document.write(row.filePath)
      this.certFileUrl = this.BASE_URL + "/udiwms/image/register/file/getImage?type=image2&name=";
      this.imgList = [];
      previewImage({imageUrl: row.filePath, certFileUrl: this.certFileUrl}).then(response => {
        if (response.code === 20000) {
          this.imgList = response.data;
        }
      });
      this.imgViewerVisible = true;
      this.imgViewer = true;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },
    closeImgViewer() {
      this.imgViewerVisible = false;
      this.imgViewer = false;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },
    onRejectSubmit() {
      this.$prompt('请输入结果说明', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.inputQuery.auditComment = value;
        this.inputQuery.auditStatus = 2;
        auditSupProduct(this.inputQuery).then(response => {
          this.loading = false;
          if (response.code === 20000) {
            this.closeRegistrationDialog(true);
            this.$message.success("保存成功");
          } else {
            this.$message.error(response.message);
          }
        });


      }).catch(() => {
      });
    },
    confirm() {
      if (this.confirmStatus == null) {
        this.$message.error("请选择确认状态");
        return;
      }
      if (this.confirmStatus == 1) {
        this.passAuditCert();
      } else if (this.confirmStatus == 2) {
        this.rejectAuditCert();
      }
    },
    cancel() {
      this.certAuditVisible = false;
    },

    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        companyName: query,
      };
      getSupComapnys(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },
    supChange(val) {
      this.pmQuery.customerId = val;
      this.findPMMethod();
    },
    findPMMethod(key) {
      this.fromPMOptions = [];
      this.pmQuery.companyName = key;
      getCompanyList(this.pmQuery)
        .then((response) => {
          this.loading = false;
          this.fromPMOptions = response.data.list || [];
          this.total = response.data.total || 0;
        })
        .catch(() => {
          this.loading = false;
          this.fromPMOptions = [];
          this.total = 0;
        });
    },
    closeLocalDialog() {
      this.addCertVisible = false;
      this.getCompanyCertList();
    },

    addCert(index, row) {
      this.idQuery.id = '';
      if (this.$isNotBlank(row) && this.$isNotBlank(row.id)) {
        this.idQuery.id = row.id;
        this.idQuery.formData = row;
      }
      this.addCertVisible = true;
    },

    deleteCompanyCert(row) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.certLoading = true;
        let tquery = {
          id: row.id,
          filePath: row.filePath,
        };
        deleteCompanyCert(tquery)
          .then((response) => {
            this.certLoading = false;
            if (response.code === 20000) {
              this.getCompanyCertList();
              this.$message({
                type: "success",
                message: "删除成功！",
              });
            } else {
              this.$message.error(response.message);
            }
          })
          .catch(() => {
            this.certLoading = false;
          });
      }).catch(() => {
      });
    },
    getCompanyCertList() {
      this.certLoading = true;
      this.certQuery.customerId = this.inputQuery.customerId;
      this.certQuery.manufacturerIdFk = this.inputQuery.manufacturerIdFk;
      this.certQuery.productIdFk = this.inputQuery.productId;
      this.certQuery.type = 3;
      filterCompanyCert(this.certQuery)
        .then((response) => {
          this.certLoading = false;
          this.certList = response.data.list || [];
          this.certTotal = response.data.total;
        })
        .catch(() => {
          this.certLoading = false;
          this.certList = [];
        });
    },
    toViewCompanyCert(row) {
      window.open(this.certFileUrl + row.filePath);
    },

    auditCert(row) {
      this.certAuditVisible = true;
      this.currentAudit = row;
      this.isOpen = this.currentAudit.auditStatus;
      this.confirmStatus = this.currentAudit.auditStatus;
    },
    revoke(inputQuery) {
      this.$confirm("是否确定撤回证书状态至未确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.certLoading = true;
        inputQuery.auditStatus = 6
        revokeSupCert(inputQuery)
          .then((response) => {
            this.certLoading = false;
            if (response.code === 20000) {
              this.getCompanyCertList();
            } else {
              this.$message.error(response.message);
            }
          })
          .catch(() => {
            this.certLoading = false;
          });
      }).catch(() => {
      });


    },

    passAuditCert() {
      this.currentAudit.auditStatus = 1;
      this.auditSupCert(this.currentAudit);
    },
    rejectAuditCert() {
      this.currentAudit.auditStatus = 2;
      this.auditSupCert(this.currentAudit);
    },


    rejectInfo(row) {
      this.$confirm(row.auditComment, "审核备注", {
        confirmButtonText: "确定",
        type: "warning",
        showCancelButton: false,
      })
        .then(() => {
        });

    },


    auditSupCert(inputQuery) {
      auditSupCert(inputQuery).then(response => {
        this.loading = false;
        if (response.code === 20000) {
          this.getCompanyCertList();
          this.certAuditVisible = false;
        } else {
          this.$message.error(response.message);
        }
      });
    },
    printSupCert(row) {
      var selectIds = [row.id];
      let query = {id: 3};
      this.loading = true;
      verifyTemplateFile(query).then((res) => {
        if (res.code === 20000) {
          let printParams = {
            templateId: res.data,
            ids: selectIds,
            id: this.inputQuery.id
          };
          printSupCertProduction(printParams).then((response) => {
            //将pdf文件转换为url。
            const binaryData = [];
            binaryData.push(response);
            //获取blob链接。
            let url = window.URL.createObjectURL(
              new Blob(binaryData, {type: "application/pdf"})
            );
            this.loading = false;
            window.open(url);//打开新标签页，预览pdf。
          })
        } else {
          this.loading = false;
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      })
    },
    printSupCertAll() {
      var certLists = this.$refs.certTable.selection;
      var selectIds = [];
      certLists.forEach(item => {
        selectIds.push(item.id);
      })
      if (selectIds.length == 0) {
        this.$message.error("请先选择打印的证书！");
        return
      }
      let query = {id: 3};
      this.loading = true;
      verifyTemplateFile(query).then((res) => {
        if (res.code === 20000) {
          let printParams = {
            templateId: res.data,
            ids: selectIds,
            id: this.inputQuery.id
          };
          printSupCertProduction(printParams).then((response) => {
            //将pdf文件转换为url。
            const binaryData = [];
            binaryData.push(response);
            //获取blob链接。
            let url = window.URL.createObjectURL(
              new Blob(binaryData, {type: "application/pdf"})
            );
            this.loading = false;
            window.open(url);//打开新标签页，预览pdf。
          })
        } else {
          this.loading = false;
          this.$message.error(res.message);
        }
      }).catch((error) => {
        this.loading = false;
        this.$message.error(error.message);
      })
    },
  },
  filters: {
    statusFilterType(status) {
      const statusMap = {
        0: "warning",
        1: "success",
        2: "danger",
        6: "warning",
      };
      return statusMap[status];
    },
  },
};
</script>
<style scoped>
.itemTag {
  float: left;
  text-align: left;
  margin-top: 10px;
  width: 120px;
}

.text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
}

.el-card {
  margin-right: 20px;
  margin-top: 15px;
  /*transition: all .5s;*/
}

.el-row {
  display: flex;
  flex-wrap: wrap;
}

.el-col {
  border-radius: 4px;
  flex-wrap: wrap;
}
</style>
