<template>
  <div>
    <el-form :model="inputQuery" :rules="rules" ref="inputQuery" label-width="100px">
      <el-card class="el-card" style="margin-top: -15px">
        <div style="float: right; ">
          <el-button type="primary" size="mini" icon="search" @click="onModifySubmit(0)">草稿保存</el-button>
          <el-button type="primary" size="mini" icon="search" @click="onModifySubmit(6)">提交审核</el-button>
        </div>
        <el-row :gutter="20" class="el-row" type="flex" style="margin-top: 35px">
          <el-col :span="10" class="el-col">
            <el-form-item label="企业名称:" label-width="150px" prop="companyName">
              <el-select v-model="inputQuery.companyName" @change="getCompanyId" placeholder="请选择企业名称" style="width: 100%">
                <el-option
                  v-for="item in maintainsList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id">
                  <span style="float: left">{{ item.name }}</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="creditNum">
              <el-input
                size="small"
                splaceholder="请输入内容"
                v-model="inputQuery.creditNum"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex" style="margin-top: 0px">
          <el-col :span="10" class="el-col">
            <el-form-item label="企业类别:" label-width="150px" prop="classes">
              <el-select
                size="small"
                v-model="inputQuery.classes"
                placeholder="企业类别"
                style="width: 100%;"
              >
                <el-option v-if="classesDisplay" label="医院" value="1"></el-option>
                <el-option label="经营企业" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="所属地区:" label-width="150px" prop="area">
              <el-cascader
                size="small"
                :options="options"
                v-model="selectedOptions"
                placeholder="请选择所属地区"
                style="width: 100%"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex" style="margin-top: 0px">
          <el-col :span="10" class="el-col">
            <el-form-item label="联系人:" label-width="150px" prop="contacts">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.contacts"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="详细地址:" label-width="150px" prop="detailAddr">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.detailAddr"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" class="el-row" type="flex" style="margin-top: 0px">
          <el-col :span="10" class="el-col">
            <el-form-item label="联系电话:" label-width="150px" prop="mobile">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.mobile"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" class="el-col">
            <el-form-item label="邮箱:" label-width="150px" prop="email">
              <el-input
                size="small"
                placeholder="请输入内容"
                v-model="inputQuery.email"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>

        <div style=" float: right;
                        text-align: right;
                        margin-bottom: 8px;"
        >

          <el-button type="primary" size="mini" icon="search" @click="selectCert"
                     style="text-align:right"
          >选入资质证书
          </el-button
          >

          <el-button type="primary" size="mini" icon="search" @click="addCert"
                     style="text-align:right"
          >添加资质证书
          </el-button
          >

        </div>

        <el-table v-loading="certLoading" :data="certList" style=" width: 100%;margin-top: 20px" border
                  highlight-current-row>
          <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="证书状态">
            <template slot-scope="scope">
              <span>{{ expire[scope.row.status] }}</span>
            </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="备注" prop="remark"></el-table-column>

          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.native="addCert(scope.row)"
                v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 2|| scope.row.auditStatus == 6"
              >编辑
              </el-button
              >
              <el-button type="text" size="mini" @click.native="showImgViewer(scope.row)">预览</el-button>
              <el-button
                type="text"
                size="small"
                v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 2|| scope.row.auditStatus == 6"
                @click.native="deleteCompanyCert(scope.row)"
              >删除
              </el-button
              >

              <el-button
                type="text"
                size="small"
                v-if=" scope.row.auditStatus == 1 && scope.row.status==0"
                @click.native="disableCert(scope.row,1)"
              >禁用
              </el-button
              >

              <el-button
                type="text"
                size="small"
                v-if=" scope.row.auditStatus == 1 && scope.row.status==1"
                @click.native="disableCert(scope.row,0)"
              >启用
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-image-viewer v-if="imgViewerVisible" style="z-index:9999" :on-close="closeImgViewer"
                         :url-list="imgList"/>
        <pagination
          v-show="certTotal>0"
          :total="certTotal"
          :page.sync="certQuery.page"
          :limit.sync="certQuery.limit"
          @pagination="certHandleCurrentChange"

        ></pagination>
      </el-card>

      <el-dialog
        title="添加资质证书"
        :visible.sync="addCertVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="70%"
        v-if="addCertVisible"
        append-to-body
        @close='closeLocalDialog'
      >
        <companyAddCert
          :closeDialog="closeLocalDialog"
          :inputQuery="inputQuery"
          :addType="addType"
          :editTye="editTye"
        ></companyAddCert>
      </el-dialog>




      <el-dialog
        title="选入资质证书"
        :visible.sync="selectCertVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        width="70%"
        v-if="selectCertVisible"
        append-to-body
        @close='closeLocalDialog'
      >
        <supCertSetSelectDialog
          :certType="certType"
          :closeDialog="closeLocalDialog"
          :customerId="customerId"
        ></supCertSetSelectDialog>
      </el-dialog>

    </el-form>
  </div>
</template>

<script>
import {modifyCompany, addCompany, bindCorp, previewImage} from "@/api/purchase/supCompany";
import store from "@/store/index";
import {regionDataPlus, CodeToText} from "element-china-area-data";
import {filterCompanyCert, deleteCompanyCert, updateCompanyCert} from "@/api/purchase/companyCert";
import corpMaintainSelect from "@/views/basic/corpMaintain/corpMaintainSelect"
import companyAddCert from "@/views/purchase/cert/supCertAddDialog";
import draggable from "vuedraggable";
import {getUUID, isBlank} from "@/utils/strUtil";
import supCertSetSelectDialog from "@/views/purchase/cert/supCertSetSelectDialog";
import {getBasicUnitMaintains, getCorpList} from "@/api/basic/basicUnitMaintain";
import ElImageViewer from "element-ui/packages/image/src/image-viewer"

export default {

  name: "supCompanyEdit",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    inputEdit: {
      type: Object,
      required: true,
    },
    editType: {
      type: Number,
      required: true,
    }
  },


  data() {
    return {
      BASE_URL: process.env.VUE_APP_BASE_API,
      headers: {},
      classesDisplay: false,
      selectedOptions: [],
      imgViewerVisible: false,
      imgList: [],
      options: regionDataPlus,
      inputQuery:{
        customerId: null,
        companyName: null,
        contacts: null,
        mobile: null,
        detailAddr: null,
      },
      rules: {
        companyName: [
          {
            required: true,
            message: "请输入企业名称",
            trigger: "blur"
          }
        ],
        creditNum: [
          {
            required: true,
            message: "请输入统一社会信用代码",
            trigger: "blur"
          }
        ],
        classes: [
          {
            required: true,
            message: "请选择企业类别",
            trigger: "change"
          }
        ],
        area: [
          {
            required: true,
            message: "请选择所属地区",
            trigger: "change"
          }
        ],
        detailAddr: [
          {
            required: true,
            message: "请输入详细地址",
            trigger: "change"
          }
        ],
        contacts: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "change"
          }
        ],
        mobile: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "change"
          }
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱",
            trigger: "change"
          }
        ],
        updateCause: [
          {
            required: true,
            message: "请输入变更原因",
            trigger: "change"
          }
        ],

      },
      uploadUrl: "",
      fileUrl: "",
      certFileUrl: "",
      url: 'http://127.0.0.1:9996/udiwms/image/register/file/getImage?type=image1&name=t11111.jpg',
      certQuery: {
        customerId: "",
        page: 1,
        limit: 20,
        type: 1
      },
      expire: {
        0: "有效",
        1: "失效"
      },
      certList: [],
      certTotal: 0,
      certLoading: false,
      addCertVisible: false,
      salesmanQuery: {
        name: "",
        page: 1,
        limit: 20
      },
      salesmanList: [],
      salesmanTotal: 0,
      salesmanLoading: false,
      addSalesmanVisible: false,
      certTypeMap: {
        1: '身份证'
      },
      selectLocalVisible: false,
      productQuery: {
        ylqxzcrbarmc: "",
        cpmctymc: "",
        ggxh: "",
        page: 1,
        limit: 20
      },
      maintainsList:[],
      productList: [],
      productTotal: 0,
      productLoading: false,
      uuid: null,
      companyApplyUpdateVisible: false,
      companyEditDisabled: true,
      companyEditButtonStr: "编辑",
      addType: "1", //证书类型：1:供应商；2.生产企业；3.产品品种
      checkFlag: {
        0: "草稿",
        1: "已通过",
        2: "已拒绝",
        3: "变更未审核",
        6: "未审核",
      },
      editTye: 1,

      selectCorpVisible: false,
      selectCertVisible: false,
      certType: 1,
      customerId: null,

    };
  }
  ,
  created() {
    if(this.editType == 1){
      this.getCompanyCertList();
    }
    // this.getBasicUnitMaintainsList();
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token,
    };
    this.inputQuery=this.inputEdit
    if (this.inputQuery.areaCode != null)
      this.selectedOptions = this.inputQuery.areaCode.split(",");
  }
  ,
  components: {
    draggable, companyAddCert, corpMaintainSelect, supCertSetSelectDialog,ElImageViewer
  }
  ,
  methods: {

    onModifySubmit(val) {

      this.inputQuery.auditStatus = val;
      if (this.editType == 0) { //新增保存

        this.$refs["inputQuery"].validate(valid => {
          if (valid) {
            this.$confirm("是否确定提交保存?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.loading = true;
              addCompany(this.inputQuery).then(response => {
                this.loading = false;
                if (response.code === 20000) {
                  this.$message.success("提交成功");
                  this.closeDialog();
                } else {
                  this.$message.error(response.message);
                }
              });
            }).catch(() => {
            });
          } else {
            return false;
          }
        });
      } else {                //编辑保存
        this.$refs["inputQuery"].validate(valid => {
          if (valid) {
            this.$confirm("是否提交变更?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.loading = true;
              modifyCompany(this.inputQuery).then(response => {
                this.loading = false;
                if (response.code === 20000) {
                  this.$message.success("提交成功");
                  this.closeDialog();
                } else {
                  this.$message.error(response.message);
                  this.inputQuery.auditStatus = 0
                }
              });
            }).catch(() => {
            });
          } else {
            return false;
          }
        });
      }
    }
    ,
    showImgViewer(row) {
      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;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },
    closeImgViewer() {
      this.imgViewerVisible = false;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },
    selectBasicCorp() {
      this.selectCorpVisible = true;
    }
    ,
    getCompanyId(){
      var row=this.maintainsList.find(item => item.id == this.inputQuery.companyName);
      this.$set(this.inputQuery,"mobile",row.mobile);
      this.$set(this.inputQuery,"customerId",row.erpId);
      this.$set(this.inputQuery,"companyName",row.name);
      this.$set(this.inputQuery,"contacts",row.contact);
      this.$set(this.inputQuery,"detailAddr",row.addr);
      this.customerId=this.inputQuery.customerId;
      console.log(this.inputQuery)
      this.getCompanyCertList();
    },

    cancelDialog() {
      this.closeDialog();
    }
    ,

    closeLocalDialog() {
      this.addCertVisible = false;
      this.selectCertVisible = false;
      this.getCompanyCertList();
    }
    ,

    handleChange(value) {
      var area = '';
      for (var i = 0; i <= 2; i++) {
        if (CodeToText[value[i]] != null && CodeToText[value[i]] != undefined) {
          area += CodeToText[value[i]];
        }
      }
      this.inputQuery.area = area;
      this.inputQuery.areaCode = value.toString();
    }
    ,

    addCert(row) {
      if(isBlank(this.inputQuery.customerId)){
        return this.$message.error("请先选择供应商");
      }

      if (this.$isNotBlank(row) && this.$isNotBlank(row.id)) {
        this.formName = 2
        this.inputQuery.formData = row;
        this.editTye = 2;
      } else {
        this.formName = 1;
        this.inputQuery.formData = {};
        this.inputQuery.formData.addType = 1;
        this.editTye = 1;
      }
      this.addCertVisible = true;
    }
    ,

    selectCert() {
      if(isBlank(this.inputQuery.customerId)){
        return this.$message.error("请先选择供应商");
      }
      this.selectCertVisible = true;
    },

    certHandleCurrentChange(val) {
      this.certQuery.page = val.page;
      this.getCompanyCertList();
    }
    ,
    getBasicUnitMaintainsList() {
      getCorpList()
        .then((response) => {
          this.maintainsList = response.data || [];
        })
        .catch(() => {
          this.maintainsList = [];
        });

    },


    getCompanyCertList() {
      this.certLoading = true;
      let certRuery = {

      }
      this.certQuery.customerId = this.inputEdit.customerId;
      console.log(this.customerId)
      filterCompanyCert(this.certQuery)
        .then((response) => {
          this.certLoading = false;
          this.certList = response.data.list || [];
          this.certTotal = response.data.total;
        })
        .catch(() => {
          this.certLoading = false;
          this.certList = [];
        });
    }
    ,

    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(() => {
      });
    }
    ,


    disableCert(row, status) {
      row.status = status;
      updateCompanyCert(row).then(response => {
        this.loading = false;
        if (response.code === 20000) {
          this.$message.success("更新成功！");
          this.getCompanyCertList();
        } else {
          this.$message.error(response.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>
