<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      size="mini"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="交易项目" prop="relationTransactionProjectId">
        <el-select
          v-model="queryParams.relationTransactionProjectId"
          placeholder="请选择交易项目"
        >
          <el-option
            v-for="item in transactionProjects"
            :key="item.transactionProjectId"
            :label="item.transactionProjectName"
            :value="item.transactionProjectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目状态" prop="tradeStatus">
        <el-select
          v-model="queryParams.tradeStatus"
          placeholder="请选择项目状态"
          clearable
          size="small"
        >
          <el-option
            v-for="item in transactionProjectStatus"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="卖方部门" prop="queryApplyDeptId">
        <div style="width: 160px">
          <treeselect
            v-model="queryParams.queryApplyDeptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择卖方部门"
          />
        </div>
      </el-form-item>

      <el-form-item label="买方部门" prop="queryTradeDeptId">
        <div style="width: 160px">
          <treeselect
            v-model="queryParams.queryTradeDeptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择买方部门"
          />
        </div>
      </el-form-item>
<!--
      <el-form-item label="发起时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetime"
          placeholder="选择日期"
        >
        </el-date-picker>
      </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="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-card class="box-card">
      <div class="outer-div">
        <header class="header">
          <ul class="tab-tilte">
            <li :class="{ active: tab == 0 }" @click="changeTab(0)">
              所有项目
            </li>
            <li :class="{ active: tab == 1 }" @click="changeTab(1)">
              我申请的
            </li>
            <li :class="{ active: tab == 2 }" @click="changeTab(2)">
              我审批的
            </li>
          </ul>
          <el-button
            @click="handleAdd"
            v-hasPermi="['system:project:add']"
            class="applyService"
            >申请服务</el-button
          >
        </header>

        <div class="tab-content">
          <!-- 可以使用自定义组件 -->
          <!-- <component-one v-show="tab == 0"></component-one>
          <component-two v-show="tab == 1"></component-two> -->
          <div v-if="tab == 0" :key="tab">
            <TableList
              :queryParams="queryParams"
              :projectList="projectList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
          <div v-if="tab == 1" :key="tab">
            <TableList
              :queryParams="queryParams"
              :projectList="projectList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
          <div v-if="tab == 2" :key="tab">
            <TableList
              :queryParams="queryParams"
              :projectList="projectList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 添加或修改交易项目对话框 -->
    <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="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="买方" prop="tradeDeptId">
              <treeselect
                v-model="form.tradeDeptId"
                :options="formDeptOptions"
                :show-count="true"
                placeholder="请选择部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="买方经办人" prop="tradeTransactor">
              <el-select v-model="form.tradeTransactor" placeholder="请选择买方经办人" style="width: 100%">
                <el-option v-for="item in transactorList"
                           :key="item.userId"
                           :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
       <el-row>
         <el-col :span="12">
           <el-form-item label="交易项目" prop="relationTransactionProjectId">
             <el-select v-model="form.relationTransactionProjectId" placeholder="请选择交易项目" style="width: 100%" @change="changeTransactionProject">
               <el-option v-for="item in transactionOptions"
                          :key="item.transactionProjectId"
                          :label="item.transactionProjectName"
                          :value="item.transactionProjectId"/>
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item v-if="priceType == '1'" label="单价" prop="tradePrice" >
             <el-input v-model="form.tradePrice" placeholder="请输入单价" :disabled="true" @blur="sumAmount"/>

           </el-form-item>

           <el-form-item v-if="priceType == '2'" label="单价" prop="tradePrice" :rules="[
          { required: false, message:'单价不能为空', trigger: 'blur' }
           ]" >
             <el-input v-model="form.tradePrice" placeholder="请输入单价" :disabled="true" @blur="sumAmount"/>
           </el-form-item>

         </el-col>
       </el-row>

       <el-row>
         <el-col :span="12">
           <el-form-item label="数量" v-if="priceType == '1'" prop="tradeCount">
             <el-input v-model="form.tradeCount" placeholder="请输入交易数量" @blur="sumAmount" :disabled="priceType == '2'"/>
           </el-form-item>
           <el-form-item label="数量" v-if="priceType == '2'" prop="tradeCount" :rules="[
          { required: false, message:'数量不能为空', trigger: 'blur' }
           ]" >
             <el-input v-model="form.tradeCount" placeholder="请输入交易数量" @blur="sumAmount" :disabled="priceType == '2'"/>
           </el-form-item>
         </el-col>
         <el-col :span="12">
           <el-form-item label="总价" prop="tradeTotal">
             <el-input v-model="form.tradeTotal" placeholder="请输入交易总价" :disabled="priceType == '1'"/>
           </el-form-item>
         </el-col>
       </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-form-item label="附件" prop="attachmentUrl">
          <FileUpload
            listType="picture"
            @resFun="getFileInfo"
            @remove="listRemove"
            :fileArr="fileList"
            :fileSize="500"
            :fileType="[
              'png',
              'jpg',
              'jpeg',
              'mp4',
              'doc',
              'xls',
              'ppt',
              'txt',
              'pdf',
            ]"
          />
          <el-input
            v-show="false"
            disabled
            v-model="form.attachmentUrl"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          style="width: 150px; border-color: #1890ff; color: #1890ff"
          @click="reset"
          >内容重置</el-button
        >
        <el-button type="primary" style="width: 150px" @click="submitForm"
          >提交申请</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selectTTradeProjectListByRoles,
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  exportProject,
} from "@/api/transaction/tradeProject.js";
import { getTransactionProjectList } from "@/api/transaction/project.js";
import { treeselect } from "@/api/system/dept";
import { selectTransactorByDeptId } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FileUpload from "@/components/FileUpload";
import uploadfile from "@/assets/uploadfile.png";
import TableList from "./components/TableList";
export default {
  name: "Project",
  components: {
    Treeselect,
    FileUpload,
    TableList,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 交易项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        queryType: "all",
        relationTransactionProjectId: null,
        applyDeptId: null,
        tradeType: null,
        tradeDeptId: null,
        tradeStatus: null,
        createTime: null,
        queryApplyDeptId: null,
        queryTradeDeptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        relationTransactionProjectId: [
          { required: true, message: "交易项目名称不能为空", trigger: "blur" },
        ],
        tradeDeptId: [
          { required: true, message: "请选择买方部门", trigger: "change" },
        ],
        tradeTransactor: [
          { required: true, message: "请选择买方经办人", trigger: "change" },
        ],
        tradePrice: [
          { required: true, message: "单价不能为空", trigger: "blur" },
        ],
        tradeCount: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        tradeTotal: [
          { required: true, message: "总价不能为空", trigger: "blur" },
        ],
      },

      transactionProjects: [],
      deptOptions: [],
      formDeptOptions: [],
      priceType: "1",
      fileList: [],
      transactionProjectStatus: [],
      tab: "0",
      transactionOptions: [],
      transactorList: [],
    };
  },
  created() {
    this.getList();
    this.getTransactionProjects();
    this.getTreeselect();
    this.getDicts("t_transaction_project_status").then((response) => {
      this.transactionProjectStatus = response.data;
    });
  },
  watch:{
    "form.tradeDeptId":{
      handler(newValue, oldValue){
        // this.changeDept();
        this.getTransactor();
      },
      deep: true,
    },
  },
  methods: {
    /** 查询交易项目列表 */
    getList(value) {
      this.loading = true;
      selectTTradeProjectListByRoles({
        ...this.queryParams,
        // pageSize: value?.limit ? value.limit : this.queryParams.pageSize,
      }).then((response) => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tradeId: null,
        receiptNum: null,
        relationTransactionProjectId: null,
        applyId: null,
        applyDeptId: null,
        applyDeptManagerId: null,
        tradeType: null,
        tradeTransactor: null,
        tradeDeptId: null,
        tradePrice: null,
        tradeCount: null,
        tradeTotal: null,
        tradeScore: null,
        tradeDeptManagerId: null,
        settlementTime: null,
        dealPrice: null,
        pendingPayment: null,
        attachmentUrl: null,
        tradeStatus: "0",
        createTime: null,
        updateTime: null,
        isDel: null,
        remark: null,
      };
      this.resetForm("form");
      this.fileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.tradeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "申请项目服务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tradeId = row.tradeId || this.ids;
      getProject(tradeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改交易项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.tradeId != 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 tradeIds = row.tradeId || this.ids;
      this.$confirm(
        '是否确认删除交易项目编号为"' + tradeIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delProject(tradeIds);
        })
        .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(() => {});
    },
    //获取项目列表
    getTransactionProjects(query) {
      getTransactionProjectList(query).then((res) => {
        if (res.code == 200) {
          this.transactionProjects = res.data;

          this.transactionOptions = this.transactionProjects.filter(item => item.deptId == this.$store.state.user.deptId);
        }
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        this.formDeptOptions = response.data;

        // 申请服务时买方不能选自己部门
        var items = this.formDeptOptions[0].children;
        var result = [];
        var j=0;
        for(var i=0; i<items.length; i++){
          if(items[i].id != this.$store.state.user.deptId){
            result[j] = items[i];
            j++;
          }
        }
        this.formDeptOptions[0].children = result;
        console.log("formDeptOptions===",this.formDeptOptions);
      });
    },
    changeTransactionProject(val) {
      let transactionProject = this.transactionProjects.find(
        (item) => item.transactionProjectId == val
      );
      if (transactionProject.priceType == "1") {
        this.priceType = "1";
        this.form.tradePrice = transactionProject.price;
      } else {
        this.priceType = transactionProject.priceType;
        this.form.tradePrice = "";
        this.form.tradeCount = "";
      }
      this.sumAmount();
    },
    //计算总价
    sumAmount() {
      if (this.form.tradePrice && this.form.tradeCount) {
        this.form.tradeTotal = this.accMul(
          this.form.tradePrice,
          this.form.tradeCount
        );
      } else {
        this.form.tradeTotal = "";
      }
    },
    //浮点计算出现无限小数
    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)
      );
    },
    getFileInfo(res) {
      this.form.attachmentUrl = res.url;
      this.fileList = [
        {
          name: res.fileName,
          url: uploadfile,
        },
      ];
    },
    listRemove(e) {
      this.fileList = [];
      this.form.attachmentUrl = "";
    },
    //切换tab
    changeTab(tabNum) {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.tab = tabNum;
      if (tabNum == 0) {
        this.queryParams.queryType = "all";
      }
      if (tabNum == 1) {
        this.queryParams.queryType = "myApply";
      }
      if (tabNum == 2) {
        this.queryParams.queryType = "myApproval";
      }
      this.getList();
    },
    changeDept() {
      this.transactionOptions = this.transactionProjects.filter(
        (item) => item.deptId == this.form.tradeDeptId
      );
      this.relationTransactionProjectId = null;
    },
    getTransactor() {
      this.form.tradeTransactor = null;
      if (this.form.tradeDeptId && this.form.tradeDeptId != null) {
        selectTransactorByDeptId({ deptId: this.form.tradeDeptId }).then(
          (res) => {
            this.transactorList = res.data;
          }
        );
      }
    },
  },
};
</script>

<style scoped lang="scss">
.outer-div {
  //padding: 24px;
  margin: 0 auto;
}
.header {
  height: 47px;
  width: 100%;
  //border-bottom: 1px solid #ebebeb;
  //margin-bottom: 24px;
}
ul li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.tab-tilte {
  font-family: PingFangSC-Semibold;
  letter-spacing: 0;
  width: 90%;
  padding-left: 0;
}
.tab-tilte li {
  float: left;
  font-size: 16px;
  color: #999999;
  // line-height: 53px;
  text-align: center;
  margin-right: 30px;
  cursor: pointer;
}
/* 点击对应的标题添加对应的背景颜色 */
.tab-tilte .active {
  color: #3385ff;
  // border-bottom: 2px solid #3385ff;
}

.applyService {
  float: right;
  width: 124px;
  border-radius: 18px;
  color: white;
  background: #1890ff;
}
</style>
