<!--零件匹配关系页-->
<template>
  <div class="cr-body-content">
    <div ref="box">
    <flexbox class="content-header">

      <el-form
        :model="listQuery"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
      >
      <!-- <span>版本:</span>

      <XhJSSelect
        :options="versionList"
        style="width: 200px"
        class="search-container"
        @value-change="selectValue"
      ></XhJSSelect> -->

      
      <el-form-item label="零件代码：" prop="partCode">
        <el-input
          v-model="listQuery.partCode"
          clearable
          size="small"
          placeholder=""
          style="width: 200px"
          class="search-container"
          @keyup.enter.native="handleFilter"
        />
      </el-form-item>
      
      <el-form-item label="零件名称：" prop="partName">
        <el-input
          v-model="listQuery.partName"
          clearable
          size="small"
          placeholder=""
          style="width: 200px"
          class="search-container"
          @keyup.enter.native="handleFilter"
        />
      </el-form-item>

      <el-form-item label="零件类型：" prop="partType">
        <el-select
          v-model="listQuery.partType"
          clearable
          placeholder="请选择"
          size="medium"
          style="margin-right: 15px"
        >
          <!-- @change="valueselectChange" -->
          <el-option
            v-for="item in partType1List"
            :key="item.id"
            :label="item.dicItemName"
            :value="item.dicItemCode"/>
        </el-select>
      </el-form-item>

      <el-form-item label="零件子类型：" prop="partType2">
        <el-select
          v-model="listQuery.partType2"
          clearable
          placeholder="请选择"
          size="medium"
          style="margin-right: 15px"
        >
          <!-- @change="valueselectChange" -->
          <el-option
            v-for="item in partType2List"
            :key="item.id"
            :label="item.dicItemName"
            :value="item.dicItemCode"/>
        </el-select>
      </el-form-item>

      <!-- <el-input
        v-model="searchContent"
        clearable
        size="small"
        placeholder="按照结算件基本信息搜索..."
        style="width: 200px"
        class="search-container"
        @keyup.enter.native="handleFilter"
      /> -->
      <el-form-item>
        <el-button
          size="mini"
          type="success"
          icon="el-icon-search"
          @click="handleFilter"
          >搜索
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery('queryForm')"
          >重置
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          class="filter-item"
          plain
          size="mini"
          type="warning"
          icon="el-icon-bottom"
          @click="handleDownload()"
          >导出Excel
        </el-button>
      </el-form-item>
			<el-form-item>
				<el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="handleImportSAP" >导入零件
</el-button>				
				
			</el-form-item>
      <!--表格头组件，filter查询-->
      <!-- <c-r-m-table-head
        ref="crmTableHead"
        :crm-type="crmType"
        @handle="handleHandle"
        @filter="handleFilters"
      >
      </c-r-m-table-head> -->
      </el-form>
    </flexbox>
    </div>
    <!--表格渲染-->
    <el-table
      ref="multipleTable"
      v-loading.fullscreen.lock="listLoading"
      element-loading-text="拼命加载中..."
      element-loading-spinner="el-icon-loading"
      class="cr-table"
      :data="list"
      :height="tableHeight"
      :cell-style="cellStyle"
      :header-cell-style="headerRowStyle"
      size="small"
      stripe
      border
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <!-- <el-table-column type="selection" width="44px"></el-table-column> -->
      <!-- <el-table-column
        label="版本"
        prop="version"
        sortable="custom"
        align="center"
        width="100px"
      >fixed 默认固定在左边
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.version" placement="top">
            <span class="link-type">{{ scope.row.version }}</span>
          </el-tooltip>
        </template>
      </el-table-column> -->
      <el-table-column
        v-for="(item, index) in getDefaultField"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :min-width="item.width"
        :formatter="fieldFormatter"
        sortable="custom"
        show-overflow-tooltip
        :gutter="0"
      >
        <template slot="header" slot-scope="scope">
          {{ scope.column.label }}
        </template>
      </el-table-column>
    </el-table>
    <div class="table-footer">
      <!-- 分页控件 style="margin-top: -25px;margin-bottom:-25px;float:right;"-->
      <pagination
        v-show="totalCount > 0"
        :total="totalCount"
        :page.sync="page"
        :limit.sync="listQuery.MaxResultCount"
        @pagination="getList"
      />
			<!-- 导入Excel组件 -->
			<importExcelCtrl ref="importexcel" :show="showExcelImport" :crmType="crmType" @close="onImportExcelDlgClosed" />			
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import permission from "@/directive/permission/index.js";
//import importExcelCtrl from "@/components/ImportExcel-invoice";
import importExcelCtrl from "@/components/ImportTxt";
import CRMTableHead from "../../components/CRMTableHead";
import moment from "moment";
import Lockr from "lockr";
import { downloadFile } from "@/utils/crmindex.js";
import XhJSSelect from "@/components/CreateCom/Xh-JS-Select-Label.vue";

export default {
  name: "CustomerPartCfg",
  components: { Pagination, CRMTableHead, importExcelCtrl, XhJSSelect },
  directives: { permission },
  filters: {
    IsCustomerSignFilter(status) {
      //翻译是否签字
      const statusMap = {
        true: "是",
        false: "否",
      };
      return statusMap[status];
    },
  },
  props: {
    customerInfos: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      crmType: "customerPartCfg",
      versionValue: "",
      //valueSelect: "R0003",
      versionList: [], //版本列表
      rules: {
        //前端定义的规则，后端也有验证
        erpMaterialCode: [
          { required: true, message: "必须输入！", trigger: "blur" },
        ],
      },
      searchContent: "", // 输入内容
      customerInfo: {
        settleAccountId: "",
      },
      form: {
        dicDetailID: "",
        customerId: "",
        projectId: "",
      },
      list: null,
      totalCount: 0,
      listLoading: true,
      formLoading: false,
      // 高级搜索
      filterObj: {
        type: Object,
        default: () => {
          return {};
        },
      },
      listVersionQuery: {
        SkipCount: 0,
        MaxResultCount: 15,
      },
      listQuery: {
        Filters: [
          {
            logic: 0,
            column: "Enabled",
            action: 0,
            value: "true",
          }, //默认查询可用的
        ],
        //OrgID:"",
        SkipCount: 0,
        MaxResultCount: 15,
        version: "",
        //site: "TH",
        customerCode: undefined,
        //userId: "00000000-0000-0000-0000-000000000000",
        partCode:"",//零件编码
        partName:"",//零件名称
        partType:"",//零件类型
        partType2:"",//零件子类型
      },
      listExportQuery: {
        Filters: [
          {
            logic: 0,
            column: "Enabled",
            action: 0,
            value: "true",
          }, //默认查询可用的
        ],
        //OrgID:"",
        SkipCount: 0,
        MaxResultCount: 15,
        version: "",
        fileType: 0,
        userId: "",
      },
      showSearch: true,
      page: 1,
      dialogFormVisible: false,
      multipleSelection: [],
      formTitle: "",
      drawer: false,
      showExcelImport: false,
			crmType: "PartCfg",
      tableHeight: document.documentElement.clientHeight - 260,
      isEdit: false,
      sortState:false, //标记刷新是否是排序调用


      
      partType1Query:{
        dicTypeName:"客户零件类型1",
      },
      partType2Query:{
        dicTypeName:"客户零件类型2",
      },

      partType1List:[],
      partType2List:[],
      
    };
  },
  mounted() {
    this.$nextTick(() => { 
        var offsetHei = document.documentElement.clientHeight;
        //console.log(offsetHei);
        let boxH = this.$refs.box.offsetHeight;
        this.tableHeight = offsetHei - boxH - 57 - 79;//57为footer高度，79为页面上部标签高度
        //console.log(this.$refs.box.offsetHeight);
        //console.log(this.tableHeight);
    });
  },
  created() {
    //this.getVersionInfo();
    //if (this.versionList == []) {
      this.getPartType();
      this.getList();
    //}
  },
  computed: {
    /** 列表字段 */
    getDefaultField() {
      var tempsTabs = [];

      tempsTabs.push({
        label: "零件代码",
        prop: "partCode",
        width: 100,
      });
      tempsTabs.push({
        label: "零件名称",
        prop: "partName",
        width: 150,
      });
      tempsTabs.push({ 
        label: "零件类型", 
        prop: "partType", 
        width: 120
      });
      tempsTabs.push({
        label: "零件子类型",
        prop: "partType2",
        width: 120,
      });
      tempsTabs.push({
        label: "零件描述",
        prop: "Description",
        width: 150,
      });
      return tempsTabs;
    },
  },
  methods: {
    selectValue(params) {
      //版本下拉选择
      this.versionValue = params.value;
      this.getList();
    },
    valueselectChange(data) {
      //alert(data);
      //版本下拉选择
      this.valueSelect = data;
      this.getList();
    },
    handleTypeDrop(command, params = {}) {
      if (command == "updateFis") {
        this.listLoading = true;
        //this.listQuery.SkipCount = (this.page - 1) * 10000;
        this.$axios
          .posts("/api/settleaccount/SettlementPart/updateFis")
          .then((res) => {
            if (res == true) {
              this.$notify({
                title: "成功",
                message: "FIS数据-更新成功！",
                type: "success",
                duration: 2000,
              });
            } else {
              this.$message({
                type: "warning",
                message: "FIS数据-更新失败！",
              });
            }
            this.listLoading = false;
          });
      } else if (command == "enter") {
      }
    },
    selectOptionsChange(item) {
      this.getList();
    },
    getVersionInfo() {
      //取版本列表信息
      //this.listLoading = true;
      this.listVersionQuery.SkipCount = (this.page - 1) * 1000;
      this.$axios
        .posts(
          "/api/settleaccount/SettlementPart/versionlist",
          this.listVersionQuery
        )
        .then((response) => {
          this.versionList = [];
          response.items.forEach((element) => {
            let options = {};
            options.value = element.id;
            options.label = element.version;
            this.versionList.push(options);
          });
          const res = new Map()
          this.versionList = this.versionList.filter((item) => !res.has(item.label) && res.set(item.label, 1))
          if (JSON.stringify(this.versionList) != "[]") {
            //因版本下拉有默认值，所以详表要自动绑定子表数据
            this.versionValue = this.versionList[0].label;
            this.getList();
          }
        })
        .catch(() => {
          //this.listLoading = false;
        });
    },
    /** 刷新列表 */
    handleHandle(data) {
      if (data.type !== "edit") {
        this.getList();
      }
    },
    /** 格式化字段 */
    fieldFormatter(row, column) {
      /* if (column.property === "state") {
        return { 0: "其他", 2: "已结" }[row[column.property]];
      }
      if (column.property == "accountDate" || column.property == "date") {
        var date = row[column.property];
        if (date == undefined) {
          return "";
        }
        //return moment(date).format("YYYY-MM-DD HH:mm:ss");
        return moment(date).format("YYYY-MM-DD");
      } */
      if(column.property === "partType")
      {
        var pl = this.partType1List.filter(u => u.dicItemCode === row[column.property]);
        if(pl.length !== 0)
        {
          var vname = pl[0].dicItemName;
          return vname;
        }
        else
        {
          return row[column.property];
        }
      }
      return row[column.property] || "--";
    },
		onImportExcelDlgClosed() {
			//关闭导入窗体时调用
			this.listLoading = false;
			this.showExcelImport = false;
			this.getList();
		},
    //导出功能
    async handleDownload() {
      this.listLoading = true;
      // if (this.versionValue === "") {
      //   this.$message.error("必需选择版本！");
      //   this.listLoading = false;
      //   return;
      // }
      // if (this.versionValue != "") {
      //   this.listQuery.version = this.versionValue;
      // }
      console.log("发票导出：" + JSON.stringify(this.listQuery));
      this.$axios
        .posts(
          "/api/newjit/part-cfg/export",
          this.listQuery
        )
        .then((res) => {
          let filename = res.item;
          this.$axios
            .BolbGets("/api/newjit/exclude-part-cfg/download/" + filename)
            .then((response) => {
              if (filename.indexOf("_") != -1) {
                let downName =
                  filename.slice(0, filename.lastIndexOf("_")) +
                  filename.slice(filename.lastIndexOf("."));
                downloadFile(response, downName);
                this.$notify({
                  title: "成功",
                  message: "数据-导出成功！",
                  type: "success",
                  duration: 2000,
                });
              } else {
                downloadFile(response, filename);
                this.$notify({
                  title: "成功",
                  message: "数据-导出成功！",
                  type: "success",
                  duration: 2000,
                });
              }
              this.listLoading = false;
            });
        });
    },
    getList() {
      this.listLoading = true;
      this.listQuery.SkipCount = (this.page - 1) * 10;
      if (this.versionValue != "") {
        this.listQuery.version = this.versionValue;
      }
      if (this.valueSelect != "") {
        this.listQuery.customerCode = this.valueSelect;
      } else {
        this.listQuery.customerCode = "";
      }
      console.log("列表查询条件：" + JSON.stringify(this.listQuery));
      this.$axios
        .gets(
          "/api/newjit/part-cfg/list",
          this.listQuery
        )
        .then((response) => {
          this.list = response.items;
          // this.list.forEach(item => {
          //   if(item.customerCode === 'R0001')
          //   {
          //     item.customerCode = '二配';
          //   }
          //   else if(item.customerCode === 'R0003')
          //   {
          //     item.customerCode = '结算';
          //   }
          // });
          this.totalCount = response.totalCount;
          setTimeout(() => {
            //大数据量加载时
            this.listLoading = false;
          }, 500);
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    fetchData(id) {
      //循环动态
      this.$axios
        .gets("/api/settleaccount/SettlementPart/" + id)
        .then((response) => {
          this.form = response;
        });
    },
    /** 筛选操作 */
    handleFilter() {
      this.page = 1;
      //#region 
      /*
      this.listQuery.Filters = [];
      if (this.partCode != "") {
        var column = "partCode";
        let filter = {
          logic: 0,
          column: column,
          action: 0,
          value: this.partCode,
        };
        this.listQuery.Filters = this.listQuery.Filters.filter(u => u.column !== "partCode")
        this.listQuery.Filters.push(filter);
      }

      if (this.partName != "") {
        var column = "partName";
        let filter = {
          logic: 0,
          column: column,
          action: 0,
          value: this.partName,
        };
        this.listQuery.Filters = this.listQuery.Filters.filter(u => u.column !== "partName")
        this.listQuery.Filters.push(filter);
      }

      if (this.partType != "") {
        var column = "partType";
        let filter = {
          logic: 0,
          column: column,
          action: 0,
          value: this.partType,
        };
        this.listQuery.Filters = this.listQuery.Filters.filter(u => u.column !== "partType")
        this.listQuery.Filters.push(filter);
      }

      if (this.partType2 != "") {
        var column = "partType2";
        let filter = {
          logic: 0,
          column: column,
          action: 0,
          value: this.partType2,
        };
        this.listQuery.Filters = this.listQuery.Filters.filter(u => u.column !== "partType2")
        this.listQuery.Filters.push(filter);
      }
      */
     //#endregion
      this.getList();
    },
    /** 多项筛选操作 */
    /** 筛选操作 */
    handleFilters(data) {
      if (data === null) {
        this.listQuery.Filters = [];
        this.getList(); //查询所有
      } else {
        console.log(data)
        this.filterObj = data;
        console.log("筛选" + JSON.stringify(data));
        var offsetHei = document.documentElement.clientHeight;
        var removeHeight = Object.keys(this.filterObj).length > 0 ? 310 : 240;
        this.tableHeight = offsetHei - removeHeight;
        this.currentPage = 1;
        let Filter = [];
        data.forEach((item) => {
          let filter = {};
          if (item.formType === "datetime" || item.formType === "datetime") {
            //日期类型的过滤条件是 (datetime >= a and  datetime <=b)
            filter["Column"] = item.fieldName;
            filter["Logic"] = 0;
            filter["Value"] = item.value[0];
            filter["Action"] = item.action;
            Filter.push(filter);

            if (item.value[1] != null) {
              filter["Value"] = item.value[1];
              filter["Action"] = 5;
              Filter.push(filter);
            }
          } else {
            filter["Column"] = item.fieldName;
            filter["Value"] = item.value;
            filter["Logic"] = 0;
            filter["Action"] = item.action;
            Filter.push(filter);
          }
        });
        console.log("筛选条件" + JSON.stringify(Filter));
        this.listQuery.Filters = Filter;
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery(refName) {
      this.$refs[refName].resetFields();
      this.getPartType()
      this.handleFilter();
    },
    sortChange(data) {
      const { prop, order } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + " " + order;
      console.log(this.listQuery.Sorting);
      if(this.listQuery.Filters.length>0 && this.listQuery.Filters[0].column === "Enabled")
      {
        this.sortState = false;
      }
      else
      {
        this.sortState = true;
      }
      this.handleFilter();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 通过回调控制style */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right" };
      } else {
        return { textAlign: "left" };
      }
    },
    /** 通过回调控制表头style */
    headerRowStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right", background: "#FAFAFA" };
      } else {
        return { textAlign: "left", background: "#FAFAFA" };
      }
    },
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    //获取零件类型
    getPartType()
    {
      this.$axios
          .gets(
            "/api/newjit/dic/list",this.partType1Query
          )
          .then((response) => {
            console.log(response);
            this.partType1List = response.item;
            //console.log()
          })
          .catch(() => {
          });
      this.$axios
          .gets(
            "/api/newjit/dic/list",this.partType2Query
          )
          .then((response) => {
            console.log(response);
            this.partType2List = response.item;
            //console.log()
          })
          .catch(() => {
          });
    },
		handleImportSAP() {
			//导入
			this.showExcelImport = true;
			this.$refs.importexcel.handleImportExcelClick();
		},
  }, //method
};
</script>


<style lang="scss" scoped>
@import "../../../pg-fis/styles/crmtable.scss";
</style>
<style lang="scss">
.el-table .cell.el-tooltip {
  white-space: pre-wrap;
}
</style>


