<template>
  <!-- 组装维护页面 -->
  <div>
    <div class="divborder newSearchDiv" style="margin:0px;">
      <!-- 产线层级 -->
      <div class="filter">
          <label >{{$t('1132')}}：</label>
          <Cascader :data="datalevel" :value="leveldata" @on-change="handlelevelchange" trigger="click" change-on-select class="searchSelect"></Cascader>
      </div>
      <!-- 产品编号 -->
      <div class="filter">
        <label>{{ $t("100089") }}：</label>
        <Select
          clearable
          filterable
          label-in-value
          class="searchSelect"
          v-model="productcode"
        >
          <Option v-for="(item,index) in productList" :value="item.name" :key="index"
            >{{ item.name }}({{ item.code }})</Option
          >
        </Select>
      </div>
      <!-- 物料编号 -->
      <div class="filter">
        <label>{{ $t("100390") }}：</label>
        <Select
          clearable
          filterable
          label-in-value
          class="searchSelect"
          v-model="materiacode"
        >
          <Option v-for="(item,index) in materialList" :value="item.pn" :key="index"
            >{{ item.pn }} {{ item.name }} {{ item.spec }}</Option
          >
        </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="Search()">{{ $t("1001") }}</Button>
        <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{ $t("1002") }}</Button>
        <Button type="warning" class="twoWord" icon="ios-create-outline" @click="edit()">{{ $t("1003") }}</Button>
        <Button type="error" class="twoWord intervalRight" icon="md-close-circle" @click="dele()">{{ $t("1004") }}</Button>
        <Button type="primary" class="fourWord" icon="md-download" @click="loadexcel()">{{ $t("1005") }}</Button>
        <Upload
              style="display:inline-block"
              ref="upload"
              :action="action"
              name="excel-file"
              :headers="headers"
              :show-upload-list="false"
              :on-format-error="handleFormatError"
              :on-success="handleSuccess"
              :on-error="handleError"
              :format="['xlsx']"
          >
              <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
        </Upload>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="Export()">{{ $t("1007") }}</Button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="divborder newTableDiv">
      <Table
        highlight-row
        class="tableClass"
        :data="tableData1"
        :columns="tableColumns1"
        @on-current-change="handleRowChange"
      ></Table>
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10, 20, 30, 40, 100]"
          ></Page>
        </div>
      </div>

      <!-- 添加/ 修改弹框 -->
      <Modal
        :title="$t(1002)"
        v-model="addmodal"
        :styles="{ width: '650px' }"
        class="newModalClass"
      >
        <p slot="header">
          <span v-if="type == 1">{{ $t("1002") }}</span>
          <span v-if="type == 2">{{ $t("1003") }}</span>
        </p>
        <div class="modal_body">
          <!-- 产线层级 -->
          <div class="filter">
              <label><i>*</i>{{$t('1132')}}：</label>
              <Cascader :data="datalevel" :value="leveldata1" @on-change="handlelevelchange1" trigger="click" change-on-select class="searchSelect"></Cascader>
          </div>
          <!-- 产品编号 -->
          <div class="filter">
            <label><i>*</i>{{ $t("100089") }}：</label>
            <Select clearable filterable label-in-value class="searchSelect" v-model="productcode1">
              <Option
                v-for="(item,index) in productList1"
                :value="item.code"
                :key="index"
                >{{ item.name }}({{ item.code }})</Option
              >
            </Select>
          </div>
          <!-- 父物料 -->
          <div class="filter">
            <label><i>*</i>父物料：</label>
            <Select clearable filterable label-in-value class="searchSelect" v-model="parent1">
              <Option
                v-for="(item,index) in parentmaterialList"
                :value="item.pn"
                :key="index"
                >{{ item.pn }}</Option
              >
            </Select>
          </div>
          <!-- 子物料 -->
          <div class="filter">
            <label><i>*</i>子物料：</label>
            <Select clearable filterable label-in-value class="searchSelect" v-model="child1">
              <Option
                v-for="(item,index) in childmaterialList"
                :value="item.pn"
                :key="index"
                >{{ item.pn }}</Option
              >
            </Select>
          </div>
          <!-- 数量 -->
          <div class="filter">
            <label><i>*</i>{{ $t("300084") }}：</label>
            <InputNumber class="searchInput" type="text" v-model="step1" :min="0"/>
          </div>
          <!-- 规则 -->
          <div class="filter">
            <label>{{ $t("600096") }}：</label>
            <Input class="searchInput" type="text" v-model="rules1" />
          </div>
        </div>
        <div slot="footer" class="footer">
          <div>
            <Button type="text" size="large" @click="addmodal = false" v-text="$t(1033)">{{ $t("1033") }}</Button>
            <Button type="primary" v-if="type == 1" size="large" @click="asyncConfirm(1)" class="myBtn" :loading="loading">
              <span v-if="!loading">{{ $t(1011) }}</span>
              <span v-else>Loading...</span>
            </Button>
            <Button type="primary" v-if="type == 2" size="large" @click="asyncConfirm(2)" :loading="loading">
              <span v-if="!loading">{{ $t(1003) }}</span>
              <span v-else>Loading...</span>
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import axios from "@/libs/api.request";
export default {
  data() {
    return {
      headers: {
          token: localStorage.getItem('token'),
          timestamp: localStorage.getItem('timestamp'),
          nonce: localStorage.getItem('nonce'),
          sign: localStorage.getItem('sign')
      },
      action:
          this.axios.publicPath +
          '/acc/Upload/UploadExcel?templateName=AssemblyMaintenanceInfo',
      leveldata: [],
      datalevel: [],
      leveldata1:[],
      productcode:'',
      materiacode:'',
      sectionid:0,
      //添加字段
      productList:[],
      productList1:[],
      parentmaterialList:[],
      childmaterialList:[],
      station1: "", //产线层级
      productcode1: "", //产品编号
      parent1: "",
      child1: "",
      step1: 0, // 顺序
      rules1: "", // 规则
      levelCount:0,

      loading: false,
      addmodal: false, // 弹框
      total: 0, // 总条数
      page: 1, // 当前页数
      pagesize: 10, // 每一页显示条数

      detailobj: {}, // 点击表格数据
      type: 0, // type 为 1 是添加操作 type 为 2 是修改操作
      materialList: [], // 选择物料
      tableData1: [], //  表格数据
      tableColumns1: [
        {
          type: "sort",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: "80px"
        },
        {
          title: this.$t("1132"), // 产线层级
          key: "station_value"
        },
        {
          title: this.$t("100089"), // 产品编号
          key: "serial_number_value"
        },
        {
          title: '父物料', // 父物料
          key: "parent_serial_value"
        },
        {
          title: '子物料', // 子物料
          key: "child_serial_value"
        },
        {
          title: this.$t("300084"), // 数量
          key: "quantity"
        },
        {
          title: this.$t("600096"), // 规则
          key: "role"
        },
        {
          title: this.$t("500030"), // 添加时间
          key: "transdatetime"
        }
      ]
    };
  },
  // 页面加载
  created() {
    this.initlevel();//产线层级
    this.Search();  // 进入调用搜索
    this.getProducts(); // 产品编号数据
    this.GetMaterialList(); // 物料编号数据
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1); // 格式化表格样式
  },
  // 事件处理
  methods: {
    initlevel () {
        axios.request({
            url: '/config/ProjectLevelSection/GetSectionTree',
            method: 'get'
        }).then(res => {
            const arr = []
            this.datalevel = res.data.data
            this.leveldata = arr

            //查询产线层级层数
            this.levelCount = this.getlevelCount(res.data.data);
        })
    },
    getlevelCount(data){
      let count = 0;
      initCount(data);
      function initCount(data){
        if(Array.isArray(data)&&data.length > 0){
          count += 1;
          data.forEach((item,index)=>{
            initCount(item.children);
          })
        }
      }
      return count;
    },
    handlelevelchange (value) {
        this.leveldata = value
        this.sectionid = 0
        if(value!=undefined&&Array.isArray(value)&&value.length >0){
          this.sectionid = value[value.length - 1];
        }
    },
    handlelevelchange1(value) {
        this.station1 = 0;
        this.leveldata1 = value
        if(value!=undefined&&Array.isArray(value)&&value.length >0){
          this.station1 = value[value.length - 1];
        }
    },
    // 监听添加事件
    add() {
      this.type = 1; // 设置 type 为 1 表示是添加操作
      this.addmodal = true; // 弹框显示
      //  置空数据
      this.leveldata1 = []
      this.station1 = '';
      this.productcode1 = '';
      this.parent1 ='';
      this.child1 = '';
      this.step1 = 0;
      this.rules1 = '';
    },
     // 弹框确定事件
    asyncConfirm(type) {
      if (!this.station1) {
        this.$Message.error(this.$t("请选择产线层级"));
        return false;
      } else if(this.leveldata1!=undefined && this.leveldata1.length != this.levelCount){
        this.$Message.error(this.$t("请选择产线层级最后一层级"));
        return false;
      } else if (!this.productcode1) {
        this.$Message.error(this.$t("产品编号必填项"));
        return false;
      } else if (!this.parent1) {
        this.$Message.error(this.$t("父物料必填项"));
        return false;
      } else if (!this.child1) {
        this.$Message.error(this.$t("子物料必填项"));
        return false;
      } else if (!this.step1) {
        this.$Message.error(this.$t("数量必须大于0"));
        return false;
      }
      let url = '';
      let id = '';
      if(this.type === 1){
        url = '/acc/AssemblyMaintenance/Add';
        id = 0;
      }else{
        url = '/acc/AssemblyMaintenance/Modify';
        id = this.detailobj.id;
      }
      var data = {
        id: id,
        lineId: 0,
        station: this.station1,
        serial_number: this.productcode1,
        parent_serial: this.parent1,
        child_serial: this.child1,
        quantity: this.step1,
        role: this.rules1
      };
      this.loading = true;
      this.axios.request({
        url: url,
        data,
        method: "post"
      })
      .then(res => {
        this.loading = false;
        if (res.data.ret === 1) {
          this.addmodal = false; // 隐藏
          if(this.type === 1){
            this.$Message.success(this.$t(1055)); // 提示
            this.Search(); // 刷新
          }else{
            this.$Message.success(this.$t(1060)); // 提示
            this.tableSearch(); // 刷新
          }
        } else {
          this.$Message.error(this.$t(res.data.msg));
        }
      });
    },
    // 产品编号数据
    getProducts() {
      axios
        .request({
          url: "/config/ProjectProduct/GetProductsByCode",
          method: "get"
        })
        .then(res => {
          let data = res.data.data;
          this.productList = []; // 初始值
          this.productList1 = []; // 初始值
          if (res.data.ret === 1&&Array.isArray(data)&&data.length > 0) {
            this.productList = data;
            this.productList1 = data;
          }
        });
    },
    // 物料编号数据
    GetMaterialList() {
      axios
        .request({
          url: "/config/Material/GetMaterialList",
          method: "get"
        })
        .then(res => {
          let data = res.data.data;
          this.materialList = []; // 初始值
          this.parentmaterialList = [];
          this.childmaterialList = [];
          if (res.data.ret === 1 &&Array.isArray(data)&&data.length > 0) {
            this.materialList = data;
            this.parentmaterialList = data;
            this.childmaterialList = data;
          }
        });
    },
    // 监听查询事件
    Search() {
      this.page = 1;
      this.pagesize = 10;
      this.tableSearch();
    },
    tableSearch() {
      this.detailobj = {};
      var params = {
        page: this.page,
        pagesize: this.pagesize,
        lineId: 0, 
        station: this.sectionid, // 产线层级
        serial_number: this.productcode, // 产品编号
        parent_serial: this.materiacode // 物料编号
      };
      axios
        .request({
          url: "/acc/AssemblyMaintenance/getList",
          params,
          method: "get"
        })
        .then(res => {
          let data = res.data.data;
          this.total = 0
          this.tableData1 = []
          if (res.data.ret === 1&&Array.isArray(data)&&data.length >0) {
            this.total = res.data.total;
            this.tableData1 = data;
          }
        });
    },
    
   
    // 监听修改事件
    edit() {
      if(this.detailobj===undefined || this.detailobj.id===undefined){
        this.$Message.error(this.$t(1017));
        return false;
      }
      this.type = 2; // 设置 type 为 1 表示是添加操作
      this.addmodal = true; // 弹框显示
      //  置空数据
      this.station1 = this.detailobj.station;
      this.productcode1 = this.detailobj.serial_number_value;
      this.parent1 =this.detailobj.parent_serial_value;
      this.child1 = this.detailobj.child_serial_value;
      this.step1 = this.detailobj.quantity;
      this.rules1 = this.detailobj.role;

      //默认选中产线层级
      this.leveldata1 = this.getChecklevel(this.station1);
    },
    getChecklevel(sectionid){
      let arr = [];
      let count = -1;
      initCheck(this.datalevel);
      function initCheck(data){
        if(Array.isArray(data)&&data.length >0){
          count += 1;
          for(var i=0;i<data.length;i++){
            if(data[i].value){
              arr[count] = data[i].value
            }
            if(data[i].value === sectionid){
              return 
            }
            else{
              initCheck(data[i].children);
            }
          }
        }
      }
      return arr;
    },
    // 监听删除事件
    dele() {
      if (!this.detailobj.id) {
        this.$Message.error(this.$t(1043));
        return false;
      } else {
        this.$Modal.confirm({
          title: this.$t("1018"),
          content: "",
          width: "290px",
          closable: true,
          okText: this.$t("1004"),
          onOk: () => {
            let params = { id: this.detailobj.id };
            axios
              .request({
                url: "/acc/AssemblyMaintenance/Delete",
                params,
                method: "get"
              })
              .then(res => {
                if (res.data.ret === 1) {
                  this.$Message.success(this.$t("1058"));
                  this.tableSearch(); // 刷新列表
                } else {
                  this.$Message.error(this.$t(res.data.msg));
                }
              });
          }
        });
      }
    },
    // 监听下载模板事件
    loadexcel() {
      this.axios
        .request({
          url: "/config/download/GetTemplate?name=AssemblyMaintenanceInfo",
          method: "get"
        })
        .then(res => {
          if (res.data.ret === 1) {
            window.location.href = this.axios.publicPath + "" + res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 监听导出事件
    Export() {
      //  请求参数
      let params = {
        lineId: 0, 
        station: this.sectionid, // 产线层级
        serial_number: this.productcode, // 产品编号
        parent_serial: this.materiacode // 物料编号
      };
      this.axios
        .request({
          url: "/acc/AssemblyMaintenance/exportAll",
          params,
          method: "get"
        })
        .then(res => {
          if (res.data.ret === 1) {
            if (res.data.data.length > 0) {
              window.location.href = this.axios.publicPath + "" + res.data.data;
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 表格点击事件
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
    },
    // 页码改变的回调，返回改变后的页码
    changePage(value) {
      this.page = value;
      this.tableSearch();
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    handlePageSize(value) {
      this.pagesize = value;
      this.tableSearch();
    },
    handleFormatError (file) {
        this.$Message.error(this.$t('920162') +
                ' ' +
                file.name +
                ' ' +
                this.$t('2010005'))
    },
    handleSuccess (res, file) {
        if (res.ret == 1) {
            this.search();
            this.$Message.success(this.$t('950398'));
        } else {
            if (('' + res.msg).indexOf(',') != -1) {
                inittip(res.msg);
            } else {
                this.$Message.error(this.$t('' + res.msg));
            }
        }
    },
    handleError () {
        this.$Message.error(this.$t('2010006') + '!');
    },
  }
};
</script>

<style lang="less" scoped>
</style>