<template>
  <div class="sys-box approve-box">
    <div class="sys-tabs">
      <el-tabs v-model="activeName">
        <el-tab-pane label="我发起的" name="first">
          <mineTabPage :disableBtn="false" :formTableData="formTableData" :searchParamElement="searchParamElement"
            :tableData="tableData" :listQuery="search_data" :total="total" :pictLoading="pictLoading" :buttons="buttons"
            :summary="summary" :showMoreSearch="true" @sortChange="sortChange" @btnClick="btnClick" @getList="getList"
            @search="search" @moreSearch="moreSearch" @goLink="gotoDetailAll" @handleCurrentChange="handleCurrentChange"
            @handleSizeChange="handleSizeChange" @getSummaries="getSummaries"
            @handleSelectionChange="handleSelectionChange"></mineTabPage>
        </el-tab-pane>
        <el-tab-pane label="我的审批" name="second">
          <span slot="label">
            <el-badge class="item" :value="approveTotal">我审批的</el-badge>
          </span>
          <auditTabPage :formTableData="showAuditColumnsDefault" :searchParamElement="searchApproveParamElement"
            :tableData="auditTableData" :listTitle="'销售订单审批'" :listQuery="approveListQuery" :total="approveTotal"
            :pictLoading="pictLoading" :buttons="buttons" @btnClick="btnClick" @getList="searchApproveList"
            @search="searchApproveList" @moreSearch="moreSearch" @gotoDetail="gotoApproveDetail"
            @handleCurrentChange="handleApproveCurrentChange" @handleSizeChange="handleApproveSizeChange"
            @handleSelectionChange="handleSelectionChange"></auditTabPage>
        </el-tab-pane>
        <el-tab-pane label="已审批的" name="fourth">
          <approvedPage :disableBtn="false" :formTableData="formTableData" :searchParamElement="searchParamElement"
            :tableData="tableData" :listQuery="search_data4" :total="total" :pictLoading="pictLoading"
            :buttons="approvedButton" :summary="summary" :showMoreSearch="true" @btnClick="btnClick" @getList="getList"
            @search="search" @moreSearch="moreSearch" @goLink="gotoDetailAll" @handleCurrentChange="handleCurrentChange"
            @handleSizeChange="handleSizeChange" @handleSelectionChange="handleSelectionChange">
          </approvedPage>
        </el-tab-pane>
        <el-tab-pane label="我的团队" name="third">
          <listTabPage :disableBtn="false" :formTableData="formTableData" :searchParamElement="searchParamElement"
            :tableData="tableData" :listQuery="search_data2" :total="total" :pictLoading="pictLoading"
            :buttons="otherButton" :summary="summary" :showMoreSearch="true" @btnClick="btnClick" @getList="getList"
            @search="search" @moreSearch="moreSearch" @goLink="gotoDetailAll" @handleCurrentChange="handleCurrentChange"
            @handleSizeChange="handleSizeChange" @handleSelectionChange="handleSelectionChange">
          </listTabPage>
        </el-tab-pane>
        <el-tab-pane label="所有列表" name="end" v-if="isExist('sales:salesContract:allList')">
          <listTabPage :disableBtn="false" :formTableData="formTableData" :searchParamElement="searchParamElement"
            :tableData="tableData" :listQuery="search_data3" :total="total" :pictLoading="pictLoading"
            :buttons="allListButton" :summary="summary" :showMoreSearch="true" @btnClick="btnClick" @getList="getList"
            @search="search" @moreSearch="moreSearch" @goLink="gotoDetailAll" @handleCurrentChange="handleCurrentChange"
            @handleSizeChange="handleSizeChange" @handleSelectionChange="handleSelectionChange">
          </listTabPage>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 状态控制 -->
    <el-dialog :title="columnSetDialogTitle" center :visible.sync="columnSetDialogVisible" width="531px"
      :before-close="handleClose">
      <el-table border class="move-table" :data="showTableColumns" row-key="prop_" :key="Math.random()" max-height="350"
        style="width: 100%">
        <el-table-column prop="title" label="列表名称"> </el-table-column>
        <el-table-column prop="select" label="是否显示">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.select"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="toUp(scope)">前移</el-button>
            <el-button type="text" size="small" @click="toDown(scope)">后移</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" class="row-bg" justify="center" style="margin-top: 10px;">
        <el-col :span="6">
          <el-button type="primary" size="middle" @click="saveAndCloseColumnSetDialog">完成</el-button>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" size="middle" @click="toDefault">恢复默认</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 高级查询对话框 -->
    <el-dialog :title="dialogTitle" center :visible.sync="advanceQueryDialogVisible" width="670px">
      <el-form :inline="true" v-loading="dialogLoading" label-width="80px" class="dialog-form" ref="form"
        style="width: 620px">
        <div class="dialog-line">
          <el-form-item label="合同时间" class="dialog-form-inline-single">
            <el-date-picker v-model="formDataTime" type="daterange" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss" range-separator="—" start-placeholder="开始时间"
              end-placeholder="结束时间"></el-date-picker>
          </el-form-item>
        </div>
        <div class="dialog-line">
          <el-form-item label="合同类型" class="dialog-form-inline">
            <el-select v-model="formData.contractType" style="width:100%" clearable placeholder="请选择"
              @change="changeFacility">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户" class="dialog-form-inline">
            <el-input placeholder="请输入客户名" v-model="formData.clientName" clearable></el-input>
          </el-form-item>
        </div>
        <div class="dialog-line">
          <el-form-item label="物料" class="dialog-form-inline">
            <btn-input :valueText.sync="formData.materielName" :valueId.sync="formData.materiel"
              :chooseVisible.sync="chooseMaterielVisible"></btn-input>
          </el-form-item>
          <el-form-item label="规格型号" class="dialog-form-inline">
            <el-input placeholder="请输入规格型号" v-model="formData.specification" clearable></el-input>
          </el-form-item>
        </div>
        <div class="dialog-line">
          <el-form-item label="销售部门" class="dialog-form-inline">
            <el-cascader v-model="salesPersonDept" clearable :options="depOptions" :props="{
              expandTrigger: 'hover',
              label: 'text',
              value: 'id',
              checkStrictly: true
            }" @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="审核状态" class="dialog-form-inline">
            <el-select v-model="formData.auditSign" style="width:100%" clearable placeholder="请选择"
              @change="changeFacility">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="dialog-line">
          <el-form-item label="销售员" prop="salesPersonName" class="dialog-form-inline">
            <btn-input :valueText.sync="formData.salesPersonName" :valueId.sync="formData.salesPerson"
              :chooseVisible.sync="chooseUserVisible"></btn-input>
          </el-form-item>
          <el-form-item label="制单人" prop="createByName" class="dialog-form-inline">
            <btn-input :valueText.sync="formData.createByName" :valueId.sync="formData.createBy"
              :chooseVisible.sync="chooseUserVisible1"></btn-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button type="primary" @click="advanceQueryDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="clear">清空</el-button>
      </span>
    </el-dialog>
    <!--选择用户-->
    <DialogChooseSingleUser :visible.sync="chooseUserVisible" @change="getUser"></DialogChooseSingleUser>
    <!--选择制单人-->
    <DialogChooseSingleUser1 :visible.sync="chooseUserVisible1" @change="getUser1"></DialogChooseSingleUser1>
    <!--选择物料-->
    <dialogChooseSingleParts :visible.sync="chooseMaterielVisible" @change="getMateriel"></dialogChooseSingleParts>
    <dialog-import-file
      v-if="showUserImportDialog"
      :visible.sync="showUserImportDialog"
      title="销售订单批量导入"
      source="sales"
      :upload-data="{ type: 'user' }"
      @success="handleUserImportSuccess"
      @close="showUserImportDialog = false"
    />
  </div>
</template>

<script>
import DialogImportFile from '@/components/Dialog/dialogImportFile.vue';
import { mapState, mapActions, mapGetters } from "vuex";
import btnInput from "@/components/btnInput.vue";
import FileSaver from "file-saver";
import config from "@/utils/config.js";
import Cookies from "js-cookie";
import DialogChooseSingleUser from "@/components/System/dialogChooseSingleUser";
import dialogChooseSingleParts from "@/components/System/dialogChooseSingleParts";
import DialogChooseSingleUser1 from "@/components/System/dialogChooseSingleUser";
import { formatDateTime, getCurrentDate } from "@/utils/tools.js";
import mineTabPage from "@/components/TabPages/mineTabPage";
import listTabPage from "@/components/TabPages/listTabPage";
import auditTabPage from "@/components/TabPages/auditTabPage";
import approvedPage from "@/components/TabPages/approvedPage";
import Sortable from "sortablejs";
export default {
  components: {
    btnInput,
    DialogChooseSingleUser,
    DialogChooseSingleUser1,
    dialogChooseSingleParts,
    mineTabPage,
    listTabPage,
    auditTabPage,
    approvedPage,
    DialogImportFile
  },
  data() {
    return {
      userUploadUrl:'/apis/standard/importExcel/sales',
      showUserImportDialog:false,
      total: 0, //总条数
      approveTotal: 0, //总条数
      pageSizes: [10, 20, 50], //每页展示多少条
      activeName: "first",
      search_data: {
        tabType: 0,
        pageno: 1,
        pagesize: 10
      },
      search_data1: {
        tabType: 0,
        pageno: 1,
        pagesize: 10
      },
      search_data2: {
        tabType: 1,
        pageno: 1,
        pagesize: 10
      },
      search_data3: {
        tabType: 2,
        pageno: 1,
        pagesize: 10
      },
      search_data4: {
        tabType: 3,
        pageno: 1,
        pagesize: 10
      },
      approveListQuery: {
        type: 3,
        pageno: 1,
        pagesize: 5
      },
      formData: {
        startTime: "",
        endTime: "",
        contractType: "",
        contractTypeName: "",
        unitUomName: "",
        clientName: "",
        materielName: "",
        specification: "",
        auditSign: "",
        salesPersonName: "",
        salesPerson: "",
        // createTime: '',
        deptId: "",
        salesPersonDept: "",
        createBy: "", //制单人id
        createByName: ""
      },
      exportList: [],
      elOptionList: [],
      searchParamElement: [
        {
          key: 0,
          label: "合同编号",
          searchType: "inputElement",
          placeholder: "合同编号",
          model: "contractCode",
          clearable: true
        },
        {
          key: 1,
          label: "客户名称",
          searchType: "inputElement",
          placeholder: "客户",
          model: "clientName",
          clearable: true
        },
        {
          key: 2,
          label: "物料名称",
          searchType: "inputElement",
          placeholder: "物料名称",
          model: "materielName",
          clearable: true
        },
        {
          key: 3,
          label: "客户合同编号",
          searchType: "inputElement",
          placeholder: "客户合同编号",
          model: "clientContractCode",
          clearable: true
        },
        {
          key: 4,
          label: "合同日期",
          searchType: "dateElement",
          placeholder: "请选择时间段",
          model: "timeArea",
          clearable: true
        }
      ],
      searchApproveParamElement: [
        {
          label: "合同编号",
          searchType: "inputElement",
          placeholder: "合同编号",
          model: "dataCode",
          clearable: true
        },
        {
          label: "客户",
          searchType: "inputElement",
          placeholder: "模糊搜索",
          model: "clientName",
          clearable: true
        },
        // {label:"物料",searchType:"inputElement",placeholder:"模糊搜索",model: "materielName",clearable:true},
        {
          label: "合同日期",
          searchType: "dateElement",
          placeholder: "请选择时间段",
          model: "timeArea",
          clearable: true
        }
      ],
      buttons: [
        {
          key: 0,
          btnName: "新增",
          vhas: "sales:salesContract:add",
          click: "goAdd",
          type: "primary",
          disabled: false
        },
        {
          key: 1,
          btnName: "删除",
          vhas: "sales:salesContract:remove",
          click: "remove",
          type: "primary",
          disabled: true
        },
        {
          key: 2,
          btnName: "导出",
          vhas: "sales:salesContract:exportExcel",
          click: "exportExcel",
          type: "primary",
          disabled: false
        },
        {
          key: 3,
          btnName: "关闭",
          vhas: "sales:salesContract:close",
          click: "close",
          type: "primary",
          disabled: true
        },
        {
          key: 4,
          btnName: "开启",
          vhas: "sales:salesContract:reverseClose",
          click: "reverseClose",
          type: "primary",
          disabled: true
        },
        {
          key: 5,
          btnName: "变更",
          vhas: "sales:salesContract:change",
          click: "change",
          type: "primary",
          disabled: true
        },
        {
          key: 6,
          btnName: "变更记录",
          vhas: "sales:salesContract:gotoAlterationList",
          click: "gotoAlterationList",
          type: "primary",
          disabled: true
        },
        {
          key: 7,
          btnName: "列表配置",
          click: "showColumnSetDialog",
          vhas: "",
          type: "primary",
          disabled: false
        },
        {
          key: 8,
          btnName: "关联单据",
          click: "associatedDocument",
          type: "primary",
          disabled: true
        },
        {
          key: 9,
          btnName: "同步ERP",
          click: "tberp",
          type: "primary",
          disabled: false
        },
        {key:10,btnName:"导入",vhas:"sales:salesContract:import",click:"importFile",type:"primary",disabled:false},

      ],
      //
      otherButton: [
        {
          key: 0,
          btnName: "导出",
          vhas: "sales:salesContract:exportExcel",
          click: "exportExcel",
          type: "primary",
          disabled: false
        },
        {
          key: 1,
          btnName: "变更记录",
          vhas: "sales:salesContract:gotoAlterationList",
          click: "gotoAlterationList",
          type: "primary",
          disabled: true
        }
      ],
      allListButton: [
        {
          key: 0,
          btnName: "导出",
          vhas: "sales:salesContract:exportExcel",
          click: "exportExcel",
          type: "primary",
          disabled: false
        },
        // {key:1,btnName:"删除",vhas:"sales:salesContract:remove",click:"remove",type:"primary",disabled:true},
        // {key:1,btnName:"反审核",vhas:"sales:salesContract:disAudit",click:"disAudit",type:"primary",disabled:true},
        {
          key: 2,
          btnName: "变更记录",
          vhas: "sales:salesContract:gotoAlterationList",
          click: "gotoAlterationList",
          type: "primary",
          disabled: true
        }
      ],
      approvedButton: [
        {
          key: 0,
          btnName: "导出",
          vhas: "sales:salesContract:exportExcel",
          click: "exportExcel",
          type: "primary",
          disabled: false
        },
        // {key:1,btnName:"删除",vhas:"sales:salesContract:remove",click:"remove",type:"primary",disabled:true},
        // {key:1,btnName:"反审核",vhas:"sales:salesContract:disAudit",click:"disAudit",type:"primary",disabled:true},
        {
          key: 2,
          btnName: "变更记录",
          vhas: "sales:salesContract:gotoAlterationList",
          click: "gotoAlterationList",
          type: "primary",
          disabled: true
        }
      ],
      //默认审批页面列表
      showAuditColumnsDefault: [
        // {title: "审批标题", prop_: "title",content:"销售订单审批", select: true},
        { title: "申请人", prop_: "approveApplicantName", select: true },
        { title: "申请时间", prop_: "submitTime", select: true },
        {
          title: "审批状态",
          prop_: "approveStatusName",
          select: true,
          sortable: true
        }
      ],
      auditTableData: [],
      //默认列表数据
      showTableColumnsDefault: [
        { title: "合同日期", prop_: "contractDate", select: true },
        { title: "合同编号", prop_: "contractCode", select: true },
        { title: "合同类型", prop_: "contractTypeName", select: true },
        { title: "客户合同编号", prop_: "clientContractCode", select: false },
        { title: "关闭标志", prop_: "closeStatusName", select: false },
        { title: "客户名称", prop_: "clientName", select: true },
        { title: "销售员", prop_: "salesPersonName", select: true },
        { title: "销售部门", prop_: "salesPersonDeptName", select: false},
        { title: "发货是否检验", prop_: "isCheck", select: false },
        { title: "物料代码", prop_: "materielSerialNo", select: true },
        { title: "物料名称", prop_: "materielName", select: false },
        { title: "规格型号", prop_: "specification", select: true },
        { title: "主计量单位", prop_: "unitUomName", select: false },
        { title: "主单位数量", prop_: "count", select: false },
        { title: "辅助单位", prop_: "supportUomName", select: false },
        { title: "销售数量", prop_: "saleCount", select: true },
        { title: "含税单价（元）", prop_: "taxUnitPrice", select: true },
        { title: "销售金额（元）", prop_: "taxAmount", select: true },
        {
          title: "交货日期",
          prop_: "deliveryDate",
          select: true,
          sortable: false
        },
        // {title: "审核状态", prop_: "auditSignName", select: true},
        { title: "审批状态", prop_: "approveStatusName", select: true },
        { title: "行关闭状态", prop_: "itemCloseStatusName", select: false },
        { title: "行关闭时间", prop_: "itemCloseTime", select: false },
        { title: "行关闭原因", prop_: "itemCloseReason", select: false }
      ],
      ///弹出页面列表数据
      showTableColumns: [
        { title: "合同日期", prop_: "contractDate", select: true },
        { title: "合同编号", prop_: "contractCode", select: true },
        { title: "合同类型", prop_: "contractTypeName", select: true },
        { title: "关闭标志", prop_: "closeStatusName", select: true },
        { title: "客户名称", prop_: "clientName", select: true },
        { title: "销售员", prop_: "salesPersonName", select: true },
        { title: "销售部门", prop_: "salesPersonDeptName", select: true },
        { title: "发货是否检验", prop_: "isCheck", select: true },
        { title: "物料代码", prop_: "materielSerialNo", select: true },
        { title: "物料名称", prop_: "materielName", select: true },
        { title: "规格型号", prop_: "specification", select: true },
        { title: "主计量单位", prop_: "unitUomName", select: true },
        { title: "主单位数量", prop_: "count", select: true },
        { title: "辅助单位", prop_: "supportUomName", select: true },
        { title: "销售数量", prop_: "saleCount", select: true },
        { title: "含税单价（元）", prop_: "taxUnitPrice", select: true },
        { title: "销售金额（元）", prop_: "taxAmount", select: true },
        {
          title: "交货日期",
          prop_: "deliveryDate",
          select: true,
          sortable: true
        },
        // {title: "审核状态", prop_: "auditSignName", select: true},
        { title: "审批状态", prop_: "approveStatusName", select: true },
        { title: "行关闭状态", prop_: "itemCloseStatusName", select: true },
        { title: "行关闭时间", prop_: "itemCloseTime", select: true },
        { title: "行关闭原因", prop_: "itemCloseReason", select: true }
      ],
      showTableColumnsTemp: [], //弹框弹出的时候，保存当前的列表数据
      //显示的列表字段
      formTableData: [],
      alterationDetailId: "",
      contractList: [],
      contractData: [],
      tableData1: [],
      summary: {},
      formDataTime: "",
      time: "",
      salesTime: "",
      tableData: [],
      depOptions: [],
      salesPersonDept: "",
      options: [],
      typeList: [],
      config: config,
      btnDelDisabled: true,
      btnOtherDisabled: true,
      advanceQueryDialogVisible: false,
      chooseUserVisible: false,
      chooseUserVisible1: false,
      chooseMaterielVisible: false, //物料
      dialogLoading: false,
      dialogTitle: "",
      pictLoading: false,
      columnSetDialogTitle: "设置显示字段列表",
      columnSetDialogVisible: false,
      salesContractIds: [],
      tableId: "sales_contract_table",
      tbody: ""
    };
  },
  watch: {
    time(val) {
      if (val) {
        this.search_data.startTime = val[0];
        this.search_data.endTime = val[1];
      } else {
        this.search_data.startTime = "";
        this.search_data.endTime = "";
      }
    },

    btnDelDisabled(val) {
      this.buttons[1].disabled = val;
      // this.allListButton[1].disabled = val
      // this.approvedButton[1].disabled = val
    },
    btnOtherDisabled(val) {
      // this.buttons[2].disabled = val
      this.buttons[3].disabled = val;
      this.buttons[4].disabled = val;
      this.buttons[5].disabled = val;
      this.buttons[6].disabled = val;
      this.buttons[8].disabled = val;
      this.otherButton[1].disabled = val;
      this.allListButton[1].disabled = val;
      // this.allListButton[3].disabled = val
      this.approvedButton[1].disabled = val;
      // this.approvedButton[3].disabled = val
    },
    activeName(val) {
      if (val === "first") {
        this.search_data = this.search_data1;
        this.getList(0);
      } else if (val === "second") {
        // this.search_data.tabType=null
      } else if (val === "third") {
        this.search_data = this.search_data2;
        this.getList();
      } else if (val === "fourth") {
        this.search_data = this.search_data4;
        this.getList();
      } else if (val === "end") {
        this.search_data = this.search_data3;
        this.getList();
      }
    },
    formDataTime(val) {
      if (val) {
        this.formData.startTime = val[0];
        this.formData.endTime = val[1];
      } else {
        this.formData.startTime = "";
        this.formData.endTime = "";
      }
    }
  },
  created() {
    this.showTableColumns = JSON.parse(JSON.stringify(this.showTableColumns));
    this.showTableColumnsTemp = JSON.parse(
      JSON.stringify(this.showTableColumns)
    );
    this.myApproveList();
    this.getList(0);
    this.getShowColumns();
    this.initData();
  },
  mounted() {
    // this.rowDrop()
    if (this.$route.query.active) {
      this.activeName = "second";
    }
  },
  methods: {
    handleUserImportSuccess(response, file, fileList) {
      this.getList()
    },
    associatedDocument() {
      let data = this.salesContractIds[0];
      this.$router.push({
        path: "/sales/salesContract_associatedDocument",
        query: {
          id: data.salesContractId,
          clientName: data.clientName,
          contractCode: data.contractCode,
          t: Date.now()
        }
      });
    },
    // 所有列表展示
    isExist(val) {
      let isExist = false;
      // 从浏览器缓存中获取权限数组
      var buttonpermsStr = localStorage.getItem("btnContext");
      if (buttonpermsStr === undefined || buttonpermsStr == null) {
        return false;
      } else {
        JSON.parse(buttonpermsStr).forEach(element => {
          //匹配缓存中的数据中有没有匹配的值
          if (element == val) {
            // 若在按钮中定义的权限字段能在后端返回的权限数组中能找到，则该按钮可显示
            isExist = true;
          }
        });
      }
      return isExist;
    },
    btnClick(val) {
      console.log("根据方法名称调用");
      if (val === "goAdd") {
        this.goAdd();
      } else if (val == "showColumnSetDialog") {
        this.showColumnSetDialog();
      } else if (val == "remove") {
        this.remove();
      } else if (val == "disAudit") {
        this.disAudit();
      } else if (val === "exportExcel") {
        this.exportExcel();
      } else if (val === "close") {
        this.close();
      } else if (val === "reverseClose") {
        this.reverseClose();
      } else if (val === "change") {
        this.change();
      } else if (val === "gotoAlterationList") {
        this.gotoAlterationList();
      } else if (val === "associatedDocument") {
        this.associatedDocument();
      } else if (val === "tberp") {
        this.tberp();
      } else if( val === 'importFile'){
        this.importFile()
      }
    },
    importFile(){
      console.log("123")
      this.showUserImportDialog = true
    },
    tberp() {
      this.$api.yxkAPI.yxkGet("/api/saleContract/u8Sync", {}).then(res => {
        if (res.code == 0) {
          this.$confirm("数据同步成功,请确认", "提醒", {
            type: "warning"
          }).then(() => {
            this.search_data = {
              tabType: 0,
              pageno: 1,
              pagesize: 10
            };
            this.getList();
          });
        }
      });
    },
    // 查询审批列表
    searchApproveList() {
      this.approveListQuery.pagesize = 5;
      this.approveListQuery.pageno = 1;
      this.myApproveList();
    },
    //进入审核页面
    gotoApproveDetail(row) {
      this.$router.push({
        path: "/sales/salesContract_approve_detail",
        query: {
          id: row.salesContractId,
          instanceId: row.instanceId,
          taskId: row.taskId,
          tabType: this.search_data.tabType,
          t: Date.now()
        }
      });
    },
    gotoDetailAll(row) {
      if (
        row.approveState == 0 ||
        row.approveState == 2 ||
        row.approveState == 3
      ) {
        this.$router.push({
          path: "/sales/salesContract_add",
          query: { id: row.salesContractId, t: Date.now() }
        });
      } else {
        this.$router.push({
          path: "/sales/salesContract_detail",
          query: { id: row.salesContractId, t: Date.now() }
        });
      }
    },
    sortChange(val) {
      console.log(val);
      this.search_data.sort = "item.delivery_date";
      this.search_data.order = val.order == "ascending" ? "asc" : "desc";
      this.getList();
    },
    myApproveList() {
      this.pictLoading = true;
      console.log(this.approveListQuery);
      this.$api.scmApproveAPI
        .myApproveList(this.approveListQuery)
        .then(res => {
          this.pictLoading = false;
          if (res.code == 0) {
            if (res.data && res.data.list) {
              this.auditTableData = res.data.list;
              this.approveTotal = res.data.total;
            } else {
              this.auditTableData = [];
              this.approveTotal = 0;
            }
            if (this.auditTableData.length) {
              this.auditTableData.forEach(item => {
                if (item.approveState == 0) {
                  item.approveStatusName = "暂存";
                } else if (item.approveState == 1) {
                  item.approveStatusName = "待审批";
                } else if (item.approveState == 2) {
                  item.approveStatusName = "已驳回";
                } else if (item.approveState == 3) {
                  item.approveStatusName = "审批通过";
                }
                item.summary = [
                  { label: "合同编号", value: item.contractCode },
                  { label: "客户", value: item.clientName },
                  { label: "合同类型", value: item.contractTypeName },
                  { label: "合同日期", value: item.contractDate },
                  { label: "合同总金额", value: item.allTaxAmount }
                ];
              });
            }
          }
        })
        .catch(r => {});
    },
    // 变更合同列表页
    gotoAlterationList() {
      let id = this.salesContractIds[0].salesContractId;
      this.$router.push({
        path: "/sales/salesContract_alterationList",
        query: { id: id, t: Date.now() }
      });
    },

    // 返回首页
    gotoIndex() {
      this.chooseProVisible = false;
    },
    // 变更
    change() {
      if (
        this.salesContractIds[0].approveStatusName === "审批通过" &&
        this.salesContractIds[0].closeStatusName === "未关闭"
      ) {
        let id = this.salesContractIds[0].salesContractId;
        this.$router.push({
          path: "/sales/salesContract_edit",
          query: { id: id, t: Date.now() }
        });
      } else {
        this.$message({
          message: "选中项已关闭或未审核",
          type: "error"
        });
      }
    },

    /**
     * 关闭
     */
    close() {
      let id = this.salesContractIds[0].salesContractId;
      this.$confirm("确认终止选中的项吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.salesAPI.closeContract({ id: id }).then(res => {
          if (res.code === 0) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.getList();
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
      });
    },
    // 反关闭
    reverseClose() {
      let id = this.salesContractIds[0].salesContractId;
      this.$confirm("确认开启选中的项吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.salesAPI.reverseClose({ id: id }).then(res => {
          if (res.code === 0) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.getList();
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
      });
    },
    // 导出
    exportExcel() {
      delete this.search_data.pagesize;
      delete this.search_data.pageno;
      this.$api.salesAPI.exportExcel(this.search_data).then(res => {});
    },
    /**
     * 反审核
     */
    disAudit() {
      let id = this.salesContractIds[0].salesContractId;
      this.$confirm("确认反审核选中的项吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.salesAPI.reverseAuditContract({ id: id }).then(res => {
          if (res.code === 0) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.getList();
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
      });
    },

    /**
     * 审核
     */
    audit() {
      let id = this.salesContractIds[0].salesContractId;
      this.$confirm("确认审核选中的项吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.salesAPI.auditContract({ id: id }).then(res => {
          if (res.code === 0) {
            this.$message({
              message: res.msg,
              type: "success"
            });
            this.getList();
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        });
      });
    },

    clickRow(row) {
      this.$refs.tb.toggleRowSelection(row);
    },

    // 跳转到查看页面
    gotoDetail(row) {
      console.log("跳转详情页面");
      this.$router.push({
        path: "/sales/salesContract_add",
        query: { id: row.salesContractId, t: Date.now() }
      });
    },

    // 前往新增页面
    goAdd() {
      this.$router.push({
        path: "/sales/salesContract_add",
        query: { t: Date.now() }
      });
    },
    liftForExport() {
      if (n == 0) {
        this.search_data1 = this.search_data;
      }
      // this.pictLoading = true;
      this.$api.salesAPI
        .listForExport(this.search_data)
        .then(res => {
          // this.pictLoading = false;
          if (res.data) {
            // this.summary = res.total
            // this.total = res.data.totalRows;
            this.exportList = res.data.list ? res.data.list : [];
            this.exportList.forEach(item => {
              // item.contractDate = item.contractDate?/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.contractDate):""
              // item.deliveryDate = item.deliveryDate?/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.deliveryDate):""
              if (item.approveState == 0) {
                item.approveStatusName = "暂存";
              } else if (item.approveState == 1) {
                item.approveStatusName = "待审批";
              } else if (item.approveState == 2) {
                item.approveStatusName = "已驳回";
              } else if (item.approveState == 3) {
                item.approveStatusName = "审批通过";
              }
            });
          } else {
            // this.total = 0;
            this.exportList = [];
          }
        })
        .catch(r => {
          console.log(r);
        });
    },
    // 获取销售订单列表
    getList(n) {
      // if(val){
      //   this.search_data.contractCode=val[0]
      //   this.search_data.clientName=val[1]
      //   this.search_data.materielName=val[2]
      // }
      if (n == 0) {
        this.search_data1 = this.search_data;
      }
      this.pictLoading = true;
      this.$api.salesAPI
        .listSalesContract(this.search_data)
        .then(res => {
          this.pictLoading = false;
          if (res.data) {
            this.summary = res.total;
            this.total = res.data.totalRows;
            this.tableData = res.data.datas ? res.data.datas : [];
            this.tableData.forEach(item => {
              // item.contractDate = item.contractDate?/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.contractDate):""
              // item.deliveryDate = item.deliveryDate?/\d{4}-\d{1,2}-\d{1,2}/g.exec(item.deliveryDate):""
              if (item.approveState == 0) {
                item.approveStatusName = "暂存";
              } else if (item.approveState == 1) {
                item.approveStatusName = "待审批";
              } else if (item.approveState == 2) {
                item.approveStatusName = "已驳回";
              } else if (item.approveState == 3) {
                item.approveStatusName = "审批通过";
              }
            });
          } else {
            this.total = 0;
            this.tableData = [];
          }
        })
        .catch(r => {
          console.log(r);
        });
    },

    //设置显示字段
    showColumnSetDialog() {
      this.columnSetDialogVisible = true;
      this.showTableColumnsTemp = JSON.parse(
        JSON.stringify(this.showTableColumns)
      );
      // 行拖拽
      // this.rowDrop()
    },
    //前移
    toUp(scope) {
      if (scope.$index == 0) {
        return false;
      }
      let n;
      for (let i = 0; i < this.showTableColumns.length; i++) {
        if (this.showTableColumns[i].prop_ == scope.row.prop_) {
          n = i;
        }
      }
      let temp = this.showTableColumns[n];
      this.showTableColumns[n] = this.showTableColumns[n - 1];
      this.showTableColumns[n - 1] = temp;
      this.$forceUpdate();
    },
    //后移
    toDown(scope) {
      if (scope.$index == this.showTableColumns.length - 1) {
        return false;
      }
      let n;
      for (let i = 0; i < this.showTableColumns.length; i++) {
        if (this.showTableColumns[i].prop_ == scope.row.prop_) {
          n = i;
        }
      }
      let temp = this.showTableColumns[n];
      this.showTableColumns[n] = this.showTableColumns[n + 1];
      this.showTableColumns[n + 1] = temp;
      this.$forceUpdate();
    },
    //恢复默认
    toDefault() {
      this.showTableColumns = JSON.parse(
        JSON.stringify(this.showTableColumnsDefault)
      );
      this.$forceUpdate();
    },
    //完成列表字段设置
    saveAndCloseColumnSetDialog() {
      let tableNo = this.tableId;
      let tableColumns = JSON.stringify(this.showTableColumns);
      this.columnSetDialogVisible = false;
      this.$api.tableColumnAPI
        .saveShowColumns({ tableNo: tableNo, tableColumns: tableColumns })
        .then(res => {
          let arr = JSON.parse(JSON.stringify(this.showTableColumns));
          this.formTableData = [];
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].select) {
              this.formTableData.push(arr[i]);
            }
          }
          this.getShowColumns();
        })
        .catch(r => {
          console.log(r);
        });
    },
    //关闭字段设置弹出
    handleClose() {
      this.showTableColumns = JSON.parse(
        JSON.stringify(this.showTableColumnsTemp)
      );
      this.columnSetDialogVisible = false;
    },
    /**
     * 获取显示字段
     */
    getShowColumns() {
      let tableNo = this.tableId;
      this.formTableData = [];

      this.$api.tableColumnAPI
        .getShowColumns({ tableNo: tableNo })
        .then(res => {
          if (res.code == 0) {
            if (res.results) {
              this.showTableColumns = JSON.parse(res.results);
              let arr = JSON.parse(JSON.stringify(this.showTableColumns));
              for (let i = 0; i < arr.length; i++) {
                if (arr[i].select) {
                  this.formTableData.push(arr[i]);
                }
              }
              this.$forceUpdate();
            } else {
              let arr = JSON.parse(
                JSON.stringify(this.showTableColumnsDefault)
              );
              for (let i = 0; i < arr.length; i++) {
                if (arr[i].select) {
                  this.formTableData.push(arr[i]);
                }
              }
              this.$forceUpdate();
            }
          } else {
            this.$message({
              message: res.msg ? res.msg : "获取列表信息失败",
              type: "error"
            });
          }
        })
        .catch(r => {
          this.$message({
            message: r,
            type: "error"
          });
          console.log(r);
        });
    },

    // 查询
    search() {
      this.search_data.pageno = 1;
      this.search_data.pagesize = 10;
      this.getList();
    },

    /**
     * 高级查询
     */
    moreSearch() {
      this.advanceQueryDialogVisible = true;
      this.dialogTitle = "高级查询";
    },
    save() {
      for (var n in this.formData) {
        this.search_data[n] = this.formData[n];
      }
      this.search_data.inDatas = "";
      this.time = this.formDataTime;
      this.search_data.pageno = 1;
      this.$nextTick(function() {
        this.advanceQueryDialogVisible = false;
        this.getList();
      });
    },
    //清空
    clear() {
      for (var n in this.formData) {
        this.formData[n] = "";
      }
      this.formDataTime = "";
      this.salesPersonDept = "";
      // this.createTime = "";
    },
    changeFacility() {
      this.$forceUpdate();
    },

    // 每页显示多少条
    handleSizeChange(val) {
      this.search_data.pagesize = val;
      this.getList();
    },
    // 上下分页
    handleCurrentChange(val) {
      this.search_data.pageno = val;
      this.getList();
    },
    // 每页显示多少条
    handleApproveSizeChange(val) {
      this.approveListQuery.pagesize = val;
      this.myApproveList();
    },
    // 上下分页
    handleApproveCurrentChange(val) {
      this.approveListQuery.pageno = val;
      this.myApproveList();
    },
    /**
     * 初始化
     */
    initData() {
      // 获取审核状态
      this.$api.salesAPI
        .listAauditSign({
          type: "audit_status"
        })
        .then(res => {
          this.options = res.datas;
        });
      //  获取合同类型
      this.$api.salesAPI
        .listContractType({
          type: "sales_contract_type"
        })
        .then(res => {
          this.typeList = res.datas;
        });
      // 获取生产部门
      Promise.all([
        this.$api.commonAPI.getDeptsTree(),
        this.$api.roleAPI.list()
      ])
        .then(([r1, r2]) => {
          if (r1.code === 0) {
            this.depOptions = r1.data.children;
            // this.setDefaultDept();
            this.setDeptList(this.depOptions);
          }
          if (r2.code === 0) {
            this.roleList = r2.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getMateriel(val) {
      if (val) {
        this.$set(this.formData, "materiel", val.id);
        this.$set(this.formData, "materielName", val.name);
      } else {
        this.$set(this.formData, "materiel", "");
        this.$set(this.formData, "materielName", "");
      }
    },

    /**
     * 获取用户
     */
    getUser(data) {
      if (data) {
        this.$set(this.formData, "salesPersonName", data.name);
        this.$set(this.formData, "salesPerson", data.id);
        //   this.formData.salesPersonName = data.name;
        //   this.formData.salesPerson = data.id;
        //   this.getUserList.forEach(item => {
        //     if (data.id === item.id) {
        //       self.formData.salesPersonDept = item.deptId;
        //         self.formData.deptId= item.deptId;
        //       return;
        //     }
        //   });
        // if (self.formData.deptId == 0) {
        //   self.formData.salesPersonDept = "";
        // }
        this.setDefaultDept();
      }
    },
    /**
     * 获取制单人
     */
    getUser1(data) {
      console.log(data);
      var self = this;
      if (data) {
        this.formData.createByName = data.name;
        this.formData.createBy = data.id;
      }
    },
    //根据当前id,获取一条树枝上的所有id数据
    treeFindPath(tree, func, path = []) {
      if (!tree) return [];
      for (const data of tree) {
        path.push(data.id);
        if (func(data)) return path;
        if (data.children) {
          const findChildren = this.treeFindPath(data.children, func, path);
          if (findChildren.length) return findChildren;
        }
        path.pop();
      }
      return [];
    },
    //当选择器选项没有下一级时，将children设置为undefined，就能选则该项了
    setDeptList(tree) {
      for (const data of tree) {
        if (!data.hasChildren) {
          data.children = undefined;
        } else {
          this.setDeptList(data.children);
        }
      }
    },
    //显示默认部门
    // setDefaultDept(){
    //     if(this.depOptions.length>0&&this.formData.deptId){
    //       let id=JSON.stringify( this.formData.deptId)
    //       let select_id=this.treeFindPath(this.depOptions,data=> data.id===id)
    //       this.salesPersonDept=JSON.parse(JSON.stringify(select_id))
    //     }
    //   },
    // 选择部门
    handleChange: function(value) {
      this.formData.salesPersonDept =
        value.length >= 1 ? value[value.length - 1] : "";
      this.salesPersonDept = value;
    },

    /**
     * 处理选中
     */
    handleSelectionChange(val) {
      this.salesContractIds = val;
      this.setBtn(val);
    },

    /**
     * 删除
     */
    remove() {
      let ids = [];
      this.salesContractIds.forEach(item => {
        ids.push(item.salesContractId);
        console.log(ids);
      });
      this.$confirm("确认删除选中的项吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.salesAPI
          .removeContract({ salesContractIds: ids })
          .then(res => {
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.search();
            } else {
              this.$message({
                message: res.msg ? res.msg : "删除失败，请重试",
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "删除失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 控件操作按钮状态
     */
    setBtn(val) {
      let isFlag = true;
      let isDelFlag = true;
      if (val.length > 0) {
        isDelFlag = false;
        if (val.length == 1) {
          isFlag = false;
        }
      } else {
        isFlag = true;
        isDelFlag = true;
      }
      this.btnDelDisabled = isDelFlag;
      this.btnOtherDisabled = isFlag;
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      console.log("zhuyemian汇总");
      console.log(param);
      let sums = [];
      columns.forEach((column, index) => {
        //计算不含税金额总计

        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property !== "count" &&
          column.property !== "taxAmount" &&
          column.property !== "saleCount"
        ) {
          sums[index] = "";
          return;
        }

        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = "";
        }
        if (column.property === "count") {
          if (sums[index]) {
            sums[index] = this.summary.totalCount;
          }
          return;
        }
        if (column.property === "saleCount") {
          if (sums[index]) {
            sums[index] = this.summary.totalSaleCount;
          }
          return;
        }
        if (column.property === "taxAmount") {
          if (sums[index]) {
            sums[index] = this.summary.totalTaxAmount;
          }
          return;
        }
      });
      console.log(this.summary);
      return sums;
    },
    //行拖拽
    rowDrop() {
      const _this = this;
      this.$nextTick(() => {
        const tbody = document.querySelector(
          ".move-table .el-table__body-wrapper tbody"
        );
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.showTableColumns.splice(oldIndex, 1)[0];
            _this.showTableColumns.splice(newIndex, 0, currRow);
          }
        });
      });
    }
  }
};
</script>
<style scoped>
.approve-box .sys-tabs .el-tabs__nav-wrap {
  padding: 5px 20px 0px;
}

.approve-box .sys-tabs .el-tabs__item {
  padding-top: 10px;
  height: 50px;
}

.approve-box .el-timeline-item__content {
  line-height: 1.5;
}

.approve-box .el-dialog__body {
  padding-top: 0px;
}
</style>
<style>
.approve-box .sys-tabs .el-tabs__nav-wrap {
  padding: 5px 20px 0px;
}

.approve-box .sys-tabs .el-tabs__item {
  padding-top: 10px;
  height: 50px;
}

.approve-box .el-timeline-item__content {
  line-height: 1.5;
}

.approve-box .el-dialog__body {
  padding-top: 0px;
}

.approve-form .el-form-item {
  margin-bottom: 0px;
}

.approve-timeline .el-timeline-item__wrapper {
  padding-top: 10px;
  padding-left: 80px;
}

.approve-timeline .el-timeline-item__tail {
  left: 30px;
  border-left-width: 4px;
}
</style>
