<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="交易项目名称" prop="transactionProjectName">
        <el-input
          v-model="queryParams.transactionProjectName"
          placeholder="请输入交易项目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="部门" prop="deptId">
        <div style="width: 200px">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" :disabled="disabled"/>
      </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="交易项目名称" align="center" prop="transactionProjectName" :show-overflow-tooltip="true"/>
      <el-table-column label="交易细项名称" align="center" prop="transactionItemName" :show-overflow-tooltip="true"/>
      <el-table-column label="交易类型" align="center" prop="priceType">
        <template slot-scope="scope">
          <span v-if="scope.row.priceType == '1'">定价</span>
          <span v-if="scope.row.priceType == '2'">议价</span>
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="price">
        <template slot-scope="scope">
          <span v-if="scope.row.price">{{scope.row.price}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:project: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" width="800px" append-to-body :close-on-click-modal="false" destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="交易项目名称" prop="transactionProjectName">
              <el-input v-model="form.transactionProjectName" placeholder="请输入交易项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易细项名称" prop="transactionItemName">
              <el-input v-model="form.transactionItemName" placeholder="请输入交易细项名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="context">
          <el-input v-model="form.context" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="定价类型" prop="priceType">
              <el-select v-model="form.priceType" placeholder="请选择定价类型" @change="changePriceType($event)">
                <el-option label="定价" value="1"/>
                <el-option label="议价" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="priceShow">
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单价"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, exportProject, importTemplate } from "@/api/transaction/project";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Project",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交易项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/transaction/project/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transactionProjectName: null,
        transactionItemName: null,
        context: null,
        priceType: null,
        price: null,
        count: null,
        total: null,
        transactor: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        transactionProjectName: [
          { required: true, message: "交易项目名称不能为空", trigger: "blur" }
        ],
        transactionItemName: [
          { required: true, message: "交易细项名称不能为空", trigger: "blur" }
        ],
        context: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        priceType: [
          { required: true, message: "请选择交易类型", trigger: "change" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "总价不能为空", trigger: "blur" }
        ],
      },
      // 部门树选项
      deptOptions: [],
      disabled:false,
      priceShow: true
    };
  },
  created() {
    if(this.$store.state.user.userId != 1){
      this.queryParams.deptId = this.$store.state.user.deptId;
      this.disabled = true;
    }

    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询交易项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transactionProjectId: null,
        transactionProjectName: null,
        transactionItemName: null,
        context: null,
        priceType: null,
        price: null,
        count: null,
        total: null,
        transactor: null,
        deptId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transactionProjectId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.priceType = "1";
      this.changePriceType(this.form.priceType);
      this.open = true;
      this.title = "添加交易项目";
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "交易项目导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transactionProjectId = row.transactionProjectId || this.ids
      getProject(transactionProjectId).then(response => {
        this.form = response.data;
        this.changePriceType(this.form.priceType);
        this.open = true;
        this.title = "修改交易项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.deptId = this.$store.state.user.deptId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.transactionProjectId != null) {
            updateProject(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transactionProjectIds = row.transactionProjectId || this.ids;
      this.$confirm('是否确认删除交易项目编号为"' + row.transactionProjectName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProject(transactionProjectIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有交易项目数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportProject(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
          this.deptOptions = response.data;
      });
    },
    //选择交易方式
    changePriceType(val){
      if(val == "1"){
        this.priceShow = true;
        this.rules.price = [{ required: true, message: "单价不能为空", trigger: "blur" }];
        //this.rules.count = [{ required: true, message: "数量不能为空", trigger: "blur" }];
      }
      if(val == "2"){
        this.priceShow = false;
        this.$delete(this.rules,"price");
        //this.$delete(this.rules,"count")
      }
    },
    //计算总价
    sumAmount(){
      if(this.form.price && this.form.count){
        this.form.total = this.accMul(this.form.price,this.form.count);
      }else{
        this.form.total = "";
      }
    },
    //浮点计算出现无限小数
    accMul(arg1,arg2){
      var m=0,s1=arg1.toString(),s2=arg2.toString();
      try{m+=s1.split(".")[1].length}catch(e){}
      try{m+=s2.split(".")[1].length}catch(e){}
      return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
    },
  }
};
</script>
