<template>
  <!-- 报工管理页面 -->
  <div>
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
        <label>{{ $t("900053") }}：</label>
          <Select clearable filterable label-in-value class="searchSelect" v-model="orderNumber">
            <Option v-for="(item,index) in orderlists" :value="item.orderNumber" :key="index"
              >{{ item.orderNumber }}</Option
            >
          </Select>
      </div>
      <div class="filter">
        <label>{{ $t("1036") }}：</label>
        <DatePicker type="datetimerange" v-model="daterange" confirm class="searchInput MaxWidth" format="yyyy-MM-dd HH:mm:ss" @on-change="selectdate"></DatePicker>
      </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("900991") }}</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>
        <!-- <btnUpload
          class="fourWord"
          @upload_success="getMsgFormbtn"
          :uploadSrc="'acc/Upload/Submit?templateName=TrParameterConfig'"
        ></btnUpload> -->
      </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="filter">
          <label><i>*</i>{{ $t("900053") }}：</label>
          <Select
            filterable
            label-in-value
            class="searchSelect"
            v-model="orderNumber1"
            @on-change="orderChange"
          >
            <Option v-for="(item,index) in orderlists" :value="item.orderNumber" :tag="index" :key="index">{{ item.orderNumber }}</Option>
          </Select>
        </div>
        <!-- 已报工数量 -->
        <div class="filter">
          <label>{{ $t("900996") }}：</label>
          <Input v-model="number1" class="searchInput" type="text" disabled />
        </div>
        <!-- 产品名称 -->
        <div class="filter">
          <label>{{ $t("100088") }}：</label>
          <Input v-model="productname1" class="searchInput" type="text" disabled />
        </div>
        <!-- 产品编号 -->
        <div class="filter">
          <label>{{ $t("100089") }}：</label>
          <Input v-model="productcode1" class="searchInput" type="text" disabled />
        </div>
        <!-- 工艺名称 -->
        <div class="filter">
          <label><i>*</i>{{ $t("950217") }}：</label>
          <Select
            filterable
            label-in-value
            class="searchSelect"
            v-model="routename1"
          >
            <Option
                  v-for="(item,index) in routeList"
                  :value="item.id"
                  :key="index"
                >
                  {{ item.process_name }}</Option
            >
          </Select>
        </div>
        <!-- 工位 -->
        <div class="filter">
          <label><i>*</i>{{ $t("1026") }}：</label>
          <Cascader
            class="searchSelect"
            trigger="click"
            :clearable="false"
            :data="datalevel1"
            :value="leveldata1"
            @on-change="handlelevelchange"
            change-on-select
          ></Cascader>
        </div>
        <!-- 人员 -->
        <div class="filter">
          <label><i>*</i>{{ $t("100046") }}：</label>
          <Select
            clearable
            filterable
            label-in-value
            class="searchSelect"
            v-model="username1"
          >
            <Option
              v-for="(item,index) in userlist"
              :value="item.id"
              :key="index"
            >
              {{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- 合格品数量 -->
        <div class="filter">
          <label><i>*</i>{{ $t("950233") }}：</label>
          <InputNumber class="searchSelect" :min="1" v-model="oknumber1"></InputNumber>
        </div>
        <!-- 工废数量 -->
        <div class="filter">
          <label><i>*</i>{{ $t("950234") }}：</label>
          <InputNumber class="searchSelect" :min="1" v-model="wastenum1"></InputNumber>
        </div>
        <!-- 废料数量 -->
        <div class="filter">
          <label><i>*</i>{{ $t("950474") }}：</label>
          <InputNumber class="searchSelect" :min="1" v-model="Wastematerials1"></InputNumber>
        </div>
        <!-- 时间 -->
        <div class="filter">
          <label><i>*</i>{{ $t("1046") }}：</label>
          <DatePicker type="datetimerange" v-model="daterange1" confirm class="searchInput MaxWidth" @on-change="selectdate1"></DatePicker>
        </div>
        <div slot="footer" class="footer">
          <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>
      </Modal>
    </div>
  </div>
</template>



<script>
import axios from "@/libs/api.request";
import moment from "moment";
import btnUpload from "../../components/upload/index";
export default {
  data() {
    return {
      loading: false,
      orderNumber: "", // 工单
      orderlists:[], //工单列表
      daterange: [], // 日期范围
      dtStart: "",
      dtEnd: "",

      //添加弹窗
      addmodal: false, // 弹框默认隐藏
      number1:0,//报工数量
      orderNumber1:'',
      productcode1:'', //产品编号
      productname1:'',//产品名称
      routename1:'',//工艺名称
      routeList:[],
      datalevel1: [], // 弹框工位数据
      leveldata1: [],
      sectionid1:0,
      username1:'',//人员
      userlist:[],//人员列表
      levelCount:0,//产线层级层数
      oknumber1:0,//合格数量
      wastenum1:0,//工费数量
      Wastematerials1:0,//料废数量
      daterange1: [], // 弹框中日期范围
      drStart1: "",
      drEnd1: "",


      total: 0, // 总条数
      page: 1, // 当前页数
      pagesize: 10, // 每一页显示条数
      tableData1: [], //  表格数据
      detailobj: {}, // 点击表格获得数据
      type: 0, // type 为 1 是添加操作 type 为 2 是修改操作
      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("900053"), // 工单
          key: ""
        },
        {
          title: this.$t("100088"), // 产品名称
          key: ""
        },
        {
          title: this.$t("100089"), // 产品编号
          key: ""
        },
        {
          title: this.$t("1950517"), // 总数量
          key: ""
        },
        {
          title: this.$t("950232"), // 工艺
          key: ""
        },
        {
          title: this.$t("1026"), // 工位
          key: ""
        },
        {
          title: this.$t("100046"), // 人员
          key: ""
        },
        {
          title: this.$t("950233"), // 合格品数量
          key: ""
        },
        {
          title: this.$t("950234"), // 工废数量
          key: ""
        },
        {
          title: this.$t("950474"), // 废料数量
          key: ""
        },

        {
          title: this.$t("950230"), // 投入时间
          key: ""
        },
        {
          title: this.$t("950231"), // 完成时间
          key: ""
        }
      ]
    };
  },
  components: {
    btnUpload
  },
  created() {
    this.initlevel();
    this.initTime();
    this.getOrderList();
  },
  // 事件处理函数
  methods: {
    initTime(){
        //时间默认一周
        var time = this.$time.changetime(3).split(' - ');
        this.dtStart = time[0]; // 时间第一项
        this.dtEnd = time[1]; // 时间第二项
        this.daterange = [time[0], time[1]]
    },
    //获取工单列表
    getOrderList(){
        var params = {
            count:999999999,
            ordernumber:''
        }
        axios.request({
          url: "/acc/ReportWorking/GetWorkOrderData",
          params,
          method: "get"
        })
        .then(res => {
          let data = res.data.data;
          this.orderlists = [];
          if (res.data.ret === 1 &&Array.isArray(data)&&data.length >0) {
            this.orderlists = res.data.data;
          }
        });
    },
    orderChange(value){
      this.number1 = 0;
      this.productname1 = '';
      this.productcode1 = '';
      if(value!=undefined){
        var index = value.tag;
        this.number1 = this.orderlists[index].reportCount;
        this.productname1 = this.orderlists[index].productName;
        this.productcode1 = this.orderlists[index].productCode;
      }
      //获取工艺名称
      this.getProcessname();
    },
    getProcessname(){
      var params = {
          code:this.productcode1,
          type:''
      };
      axios
          .request({
              url: '/acc/Routing/GetProcessData',
              params,
              method: 'get'
          })
          .then(res => {
            this.routeList = []
            if(res.data.ret ===1 && res.data.data!=null&&res.data.data!=undefined){
              this.routeList = res.data.data;
            }
          });
    },
    // 首页时间处理函数
    selectdate(e) {
      this.dtStart = e[0]; // 时间第一项
      this.dtEnd = e[1]; // 时间第二项
      let last_str = this.dtEnd.split(" ")[1];
      if (last_str === "00:00:00") {
        this.dtEnd = moment(this.dtEnd).format("YYYY-MM-DD") + "23:59:59";
      }
      this.daterange = [this.dtStart, this.dtEnd];
    },
    // 弹框页面时间处理函数
    selectdate1(e) {
      this.drStart1 = e[0]; // 时间第一项
      this.drEnd1 = e[1]; // 时间第二项
      let last_sto = this.drEnd1.split(" ")[1];
      if (last_sto === "00:00:00") {
        this.drEnd1 = moment(this.drEnd1).format("YYYY-MM-DD") + "23:59:59";
      }
      this.daterange1 = [this.drStart1, this.drEnd1];
    },
    // 获取人员信息
    GetUsers() {
      //获取人员
      var params = {
          page: 1,
          pagesize: 9999999
      };
      axios
          .request({
              url: '/config/user/GetUsers',
              params,
              method: 'get'
          })
          .then(res => {
            this.userlist = []
            if(res.data.ret ===1 && res.data.data!=null&&res.data.data!=undefined){
              this.userlist = res.data.data;
            }
          });
    },
    initlevel() {
      axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionTree",
          methods: "get"
        })
        .then(res => {
          const arr = [];
          if (
            res.data.ret === 1 &&
            res.data.data != null &&
            res.data.data != undefined &&
            res.data.data.length
          ) {
            this.datalevel1 = res.data.data;
            this.leveldata1 = 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.leveldata1 = [];
      this.sectionid1 = 0;
      if(value!=undefined){
        this.leveldata1 = value;
        this.sectionid1 = value[value.length - 1];
      }
    },
    // 监听报工事件
    add() {
      this.type = 1; // 设置 type 为 1 表示是添加操作
      this.addmodal = true;
      this.GetUsers();
      // 清空数据
      this.number1 = 0;//报工数量
      this.orderNumber1 = '';
      this.productcode1 = ''; //产品编号
      this.productname1 = '';//产品名称
      this.routename1 = '';//工艺名称
      this.leveldata1 = [];
      this.sectionid1 = 0;
      this.username1 = '';//人员
      this.oknumber1 = 0;//合格数量
      this.wastenum1 = 0;//工费数量
      this.Wastematerials1 = 0;//料废数量
      this.daterange1 = [];
      this.drStart1 =  "";
      this.drEnd1 = "";
      
    },
    // 弹框确定事件
    asyncConfirm(type) {
      if (!this.orderNumber1) {
        this.$Message.error(this.$t('1114'));
        return false;
      }  else if (!this.routename1) {
        this.$Message.error(this.$t('950463'));
        return false;
      } else if (!this.sectionid1 || this.leveldata1.length != this.levelCount) {
        this.$Message.error(this.$t('1052'));
        return false;
      } else if (!this.username1) {
        this.$Message.error(this.$t('200161'));
        return false;
      } else if (!this.oknumber1) {
        this.$Message.error(this.$t('请填写合格品数量'));
        return false;
      } else if (!this.wastenum1) {
        this.$Message.error(this.$t('请填写工废数量'));
        return false;
      } else if (!this.Wastematerials1) {
        this.$Message.error(this.$t('请填写废料数量必填项'));
        return false;
      } else if (this.daterange1.length == 0) {
        this.$Message.error(this.$t('500124'));
        return false;
      }
      var time = '';
      if(this.daterange1!=''&&this.daterange1!=undefined&&this.daterange1.length > 0){
        time = moment(this.daterange1[0]).format("YYYY-MM-DD HH:mm:ss") + ' - ' + moment(this.daterange1[1]).format("YYYY-MM-DD HH:mm:ss");
      }

      let id = 0;
      let url = '';
      if(type === 1){
        id = 0;
        url = '/acc/ReportWorking/AddProduceReport';
      }else{
        id = this.detailobj.id;
        url = '/acc/ReportWorking/ModifyProduceReport';
      }
      // 组装请求参数 (前边所有的字段待确认)
      var data = {
        id:id,
        section:this.sectionid1,
        uid:this.username1,
        okcount:this.oknumber1,
        industrial_waste:this.wastenum1,
        material_waste:this.Wastematerials1,
        time:time,
        code:this.oknumber1,
        processid:this.routename1
      }
      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(type===1){
              this.$Message.success(this.$t(1055)); // 提示
              this.toSearch(); // 刷新
            }else{
              this.$Message.success(this.$t(1060)); // 提示
              this.Search(); // 刷新
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    // 监听查询事件
    Search() {
      this.page = 1;
      this.pagesize = 10;
      this.tableSearch();
    },
    // (搜索有问题... 报错)
    tableSearch() {
      this.detailobj = {};
      var data = {
        page: this.page,
        pagesize: this.pagesize,
        orderNumber: this.orderNumber, // 工单
        startTime: this.dtStart, // 开始时间
        endTime: this.dtEnd // 结束时间
      };
      axios
        .request({
          url: "/acc/ReportWorking/GetProductReportData",
          data,
          method: "post"
        })
        .then(res => {
          console.log(res);
          //  return false;
          if (res.data.ret === 1) {
            this.total = res.data.total;
            this.tableData1 = res.data.data;
            this.page = res.data.page;
          }
        });
    },
    // 监听修改事件
    edit() {
      if (!this.detailobj.id) {
        this.$Message.error(this.$t(1043));
        return false;
      }
      this.type = 2; // type 为 2 表示修改
      this.addmodal = true;
    },
    // 监听删除事件
    dele() {
      if (!this.detailobj.id) {
        this.$Message.error(this.$t(1043));
        return false;
      }
    },
    // 表格点击事件
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
    },
    // 页码改变的回调，返回改变后的页码
    changePage(value) {
      this.page = value;
      this.tableData1 = this.tableSearch(this.page, this.pagesize);
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    handlePageSize(value) {
      this.pagesize = value;
      this.tableData1 = this.tableSearch(this.page, this.pagesize);
    }
  }
};
</script>

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