<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="指标名称" prop="quotaName">
        <el-input v-model="queryParams.quotaName"></el-input>
      </el-form-item>
      <el-form-item label="保税区名称" prop="bondedName">
        <el-select v-model="queryParams.bondedName" placeholder="请选择保税区" clearable filterable @change="selectBondedChange" style="width:100%">
          <el-option
            v-for="item in deptList"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:QUOTABONDED:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:QUOTABONDED:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:QUOTABONDED:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table :data="QUOTABONDEDList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="保税区名称"
        align="center"
        prop="bondedName"
        width="140"
      ></el-table-column>
      <el-table-column
        label="指标名称"
        align="center"
        prop="quotaName"
        width="180"
      ></el-table-column>
      <el-table-column
        label="得分"
        align="center"
        prop="score"
      ></el-table-column>
      <el-table-column
        label="录入方式"
        align="center"
        prop="enterType"
      ></el-table-column>
      <el-table-column
        label="数值"
        align="center"
        prop="numValue"
      ></el-table-column>
      <el-table-column
        label="文字说明"
        align="center"
        prop="remark"
        width="280"
      ></el-table-column>
      <el-table-column label="附件" align="center" prop="fileNames" width="80">
        <template slot-scope="scope">
          <el-link style="text-decoration: underline;color: #36aafd" @click="download(scope.row.fileNames)">{{scope.row.fileNames}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == null"
            size="mini"
            type="text"
            @click="handleApprove(scope.row)"
            v-hasPermi="['business:QUOTABONDED:remove']"
            >提交审核</el-button
          >

          <el-button
            v-if="
              scope.row.auditStatus == 1 &&
              (scope.row.approvalStatus == 0 ||
                scope.row.approvalStatus == null)
            "
            size="mini"
            type="text"
            @click="handleAdminApprove(scope.row)"
            v-hasPermi="['business:QUOTABONDED:remove']"
            >审核</el-button
          >

          <el-button
            v-if="scope.row.approvalStatus == 1 && (scope.row.reportStatus == 0 || scope.row.reportStatus == null)"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleReport(scope.row)"
            v-hasPermi="['business:QUOTABONDED:remove']"
            >上报</el-button
          >
          <el-button
            v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:QUOTABONDED:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:QUOTABONDED:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改辅助指标-综保区对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label-width="100px" label="保税区" prop="bondedName">
          <el-select
            :disabled="isAppoval"
            v-model="form.bondedName"
            placeholder="请选择保税区"
            clearable
            filterable
            @change="selectBondedChange"
            style="width: 100%"
          >
            <!--            <el-option v-for="dict in BONDEDList" :key="dict.id" :label="dict.bondedName" :value="dict" />-->
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="100px" label="辅助指标" prop="quotaName">
          <el-select
            :disabled="isAppoval"
            v-model="form.quotaName"
            placeholder="请选择辅助指标"
            clearable
            filterable
            @change="selectQuotaChange"
            style="width: 100%"
          >
            <el-option
              v-for="dict in QUOTAFEEList"
              :key="dict.id"
              :label="dict.quotaName"
              :value="dict"
            />
          </el-select>
        </el-form-item>

        <el-form-item label-width="100px" label="录入方式" prop="enterType">
          <el-select
            :disabled="isAppoval"
            v-model="form.enterType"
            placeholder="请选择录入方式"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option value="附件">附件</el-option>
            <el-option value="文字说明">文字说明</el-option>
            <el-option value="数值">数值</el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="form.enterType == '附件'"
          label-width="100px"
          prop="linkUrls"
          label="上传附件"
        >
          <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            :file-list="fileList"
            :auto-upload="false"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :multiple="true"
          >
            <div v-if="isAppoval" slot="tip" class="el-upload__tip">
              审核无法修改
            </div>
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item
          v-if="form.enterType == '文字说明'"
          label-width="100px"
          prop="remark"
          label="说明"
        >
          <el-input
            type="textarea"
            :disabled="isAppoval"
            v-model="form.remark"
            rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="form.enterType == '数值'"
          label-width="100px"
          prop="numValue"
          label="数值"
        >
          <el-input :disabled="isAppoval" v-model="form.numValue"></el-input>
        </el-form-item>

        <el-form-item label-width="100px" prop="score" label="分值">
          <el-input :disabled="isAppoval" v-model="form.score"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" v-if="!isAppoval" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <div slot="footer" v-else class="dialog-footer">
        <el-button type="primary" @click="setRejectAndResolve('resolve')"
          >通 过</el-button
        >
        <el-button type="warning" @click="setRejectAndResolve('reject')"
          >驳 回</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listQUOTABONDED,
  getQUOTABONDED,
  delQUOTABONDED,
  addQUOTABONDED,
  updateQUOTABONDED,
  setApprove,
  setAdminApprove,
  setAdminReport,
} from "@/api/norm/QUOTABONDED";


import { listQUOTAFEE } from "@/api/norm/QUOTAFEE";
import { listBONDED } from "@/api/portal/BONDED/BONDED.js";
import { uploadFiles, downloadFiles } from "@/api/common";
import { listDept } from "@/api/system/dept";

export default {
  name: "QUOTABONDED",
  data() {
    return {
      isAppoval: false,
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 辅助指标-综保区表格数据
      QUOTABONDEDList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      QUOTAFEEList: [],
      BONDEDList: [],
      fileList: [],
      // 保税区列表
      deptList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        deptId: null,
        bondedId: null,
        bondedName: null,
        quotaId: null,
        quotaName: null,
        score: null,
        status: null,
        startTime: null,
        stopTime: null,
        linkUrls: null,
        remark: null,
        fileNames: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bondedName: [
          { required: true, message: "综保区名称不能为空", trigger: "blur" },
        ],
        quotaName: [
          { required: true, message: "指标名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    listQUOTAFEE().then((response) => {
      response.rows.forEach((item, index) => {
        response.rows[index].status = item.status == 0 ? false : true;
      });
      this.QUOTAFEEList = response.rows;
    });
    listBONDED().then((response) => {
      this.BONDEDList = response.rows;
    });
    this.getList();
    this.getDeptList();

  },
  methods: {
    // 获取保税区列表
    getDeptList() {
      this.loading = true;
      listDept({ parentId: "100" }).then((response) => {
        this.deptList = response.data;
        this.loading = false;
      });
    },
    selectBondedChange(val) {
      const selectedDept = this.deptList.find(
        (item) => item.deptName === this.form.bondedName
      );
      if (selectedDept) {
        this.form.bondedId = selectedDept.deptId;
      }
      // this.form.bondedId = val.id;
      // this.form.bondedName = val.bondedName;
    },
    selectQuotaChange(val) {
      this.form.quotaId = val.id;
      this.form.quotaName = val.quotaName;
    },
    /** 查询辅助指标-综保区列表 */
    getList() {
      this.loading = true;
      listQUOTABONDED(this.queryParams).then((response) => {
        this.QUOTABONDEDList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        deptId: null,
        bondedId: null,
        bondedName: null,
        quotaId: null,
        quotaName: null,
        score: null,
        status: "1",
        startTime: null,
        stopTime: null,
        linkUrls: null,
        remark: null,
        fileNames: null,
        enterType: null,
        numValue: null,
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAppoval = false;
      this.reset();
      this.open = true;
      this.title = "辅助指标录入新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getQUOTABONDED(id).then((response) => {
        this.form = response.data;
        this.form.linkUrls = this.baseURL + response.data.linkUrls;
        this.fileList = [];
        this.fileList.push({
          name: response.data.fileNames,
          url: response.data.linkUrls,
        });
        this.open = true;
        this.title = "辅助指标录入修改";
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (!(parseInt(this.form.score) == this.form.score)) {
            this.$message.error("得分必须为整数");
            return;
          }
          if (this.form.enterType == '文字说明' && this.form.remark == null) {
            this.$message.error("请录入文字说明");
            return;
          }
          if (this.form.enterType == "数值" && this.form.numValue == null) {
            this.$message.error("请录入数值");
            return;
          }
          if (
            this.form.numValue != null &&
            !(
              parseInt(this.form.numValue) == this.form.numValue ||
              parseFloat(this.form.numValue) == this.form.numValue
            )
          ) {
            this.$message.error("数值必须为整数或小数");
            return;
          }
          if (this.form.id != null) {
            if (this.form.enterType == '附件') {
              if(this.fileList.length < 1) {
                this.$message.error("请选择文件传输！");
                return;
              } else {
                let formData = new FormData()
                this.fileList.forEach((item) => {
                  formData.append("file", item.raw);
                });
                uploadFiles(formData).then(res=>{
                  if(res.code == 200){
                    this.form.linkUrls = res.fileNames;
                    this.form.fileNames = res.newFileNames;

                    updateQUOTABONDED(this.form).then(response => {
                      this.$modal.msgSuccess("修改成功");
                      this.open = false;
                      this.getList();
                    });
                  }
                })
              }
            } else {
              updateQUOTABONDED(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            if (this.form.enterType == '附件') {
              if(this.fileList.length < 1) {
                this.$message.error("请选择文件传输！");
                return;
              } else {
                let formData = new FormData()
                this.fileList.forEach((item) => {
                  formData.append("file", item.raw);
                });
                uploadFiles(formData).then(res=>{
                  if(res.code == 200){
                    this.form.linkUrls = res.fileNames;
                    this.form.fileNames = res.newFileNames;

                    addQUOTABONDED(this.form).then(response => {
                      this.$modal.msgSuccess("新增成功");
                      this.open = false;
                      this.getList();
                    });
                  }
                })
              }
            } else {
              addQUOTABONDED(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    // 管理员驳回审核
    setRejectAndResolve(type) {
      let val;
      if (type == "resolve") {
        val = 1;
      } else {
        val = 2;
      }
      setAdminApprove({ quotoBondedId: this.form.id, type: val }).then((res) => {
        if (res.code == 200) {
          this.$message.success(val == 1 ? "审核成功":"驳回成功");
          this.getList();
          this.open = false;
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除辅助指标-综保区编号为"' + ids + '"的数据项？')
        .then(function () {
          return delQUOTABONDED(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    // 用户提交审核
    handleApprove(data) {
      setApprove({ quotoBondedId: data.id }).then((res) => {
        if (res.code == 200) {
          this.$message.success("提交成功");
          this.getList();
        }
      });
    },
    // 管理审核审核
    handleAdminApprove(row) {
      this.reset();
      const id = row.id || this.ids;
      this.isAppoval = true;
      getQUOTABONDED(id).then((response) => {
        this.form = response.data;
        this.form.linkUrls = this.baseURL + response.data.linkUrls;
        this.fileList = [];
        this.fileList.push({
          name: response.data.fileNames,
          url: response.data.linkUrls,
        });
        this.open = true;
        this.title = "辅助指标录入修改";
      });
    },
    // 管理上报
    handleReport(data) {
      setAdminReport({ quotoBondedId: data.id, type: 1 }).then((res) => {
        if (res.code == 200) {
          this.$message.success("上报成功");
          this.getList();
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/QUOTABONDED/export",
        {
          ...this.queryParams,
        },
        `QUOTABONDED_${new Date().getTime()}.xlsx`
      );
    },

    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    download(resource) {
      let fileNames = resource.split(',');
      fileNames.forEach(item => {
         downloadFiles('/profile/upload/' +item);
      })
    }
  }
};
</script>
