<template>
  <!-- 新增工机具 -->
  <div>
    <el-form
      :model="maForm"
      ref="maForm"
      size="small"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="类型规格" prop="keyWord">
        <el-input
          v-model="maForm.keyWord"
          placeholder="请输入类型规格"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="机具厂家" prop="typeId">
        <el-select
          v-model="maForm.typeId"
          placeholder="请选择机具厂家"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="typeItem in typesList"
            :key="typeItem.typeId"
            :label="typeItem.typeName"
            :value="typeItem.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出厂日期" prop="arrivalTime">
        <el-date-picker
          v-model="maForm.arrivalTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="date"
          placeholder="请选择出厂日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBackAll"
          >驳回</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="equipmentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column
        align="center"
        label="物资名称"
        prop="materialName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="规格型号"
        prop="materialModel"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="到货数量"
        prop="checkNum"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="单位" prop="unitName" />
      <el-table-column
        align="center"
        label="供应商"
        prop="supplierName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="出厂日期"
        prop="productDate"
        show-overflow-tooltip
      />

      <el-table-column label="相关配套资料" align="center" prop="checkUrlName">
        <!-- <template slot-scope="scope">
            <div @click="openGt(scope.row)" style="color: #02a7f0; cursor: pointer">
                {{ '报告管理' }}
            </div>
            </template> -->
      </el-table-column>

      <el-table-column
        align="center"
        label="状态"
        prop="statusName"
        show-overflow-tooltip
      />

      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-zoom-in"
            @click="handleView(scope.row)"
            v-if="scope.row.statusName == '待入库'"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-zoom-in"
            @click="handleBind(scope.row)"
            v-if="scope.row.statusName != '待入库'"
            >绑定</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleBack(scope.row)"
            v-if="scope.row.statusName != '待入库'"
            >驳回</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="maForm.pageNum"
      :limit.sync="maForm.pageSize"
      @pagination="getListPeople"
    />

    <!-- 新购查看弹窗 -->
    <el-dialog
      :title="titleBind"
      :visible.sync="showBind"
      width="1000px"
      append-to-body
    >
      <el-form
        :model="queryBind"
        ref="queryFormBind"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
      </el-form>
      <el-table
        v-loading="loadingTwo"
        :data="getListPeople"
        width="800px"
        height="600px"
      >
        <!-- <el-table-column label="序号" align="center" prop="userName" sortable /> -->
        <el-table-column
          label="类型名称"
          align="center"
          prop="materialName"
          sortable
        />
        <el-table-column
          label="规格型号"
          align="center"
          prop="materialModel"
          sortable
        />
        <el-table-column
          label="设备编码"
          align="center"
          prop="maCode"
          sortable
        />
        <el-table-column
          label="绑定人员"
          align="center"
          prop="createBy"
          sortable
        />
        <el-table-column
          label="绑定时间"
          align="center"
          prop="createTime"
          sortable
        />
        <el-table-column
          label="出厂编号"
          align="center"
          prop="outFacCode"
          sortable
        />
        <el-table-column
          label="出厂时间"
          align="center"
          prop="productDate"
          sortable
        />
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryBind.pageNum"
        :limit.sync="queryBind.pageSize"
        @pagination="getListPeople"
      />
    </el-dialog>

    <!-- 绑定查看弹窗 -->
    <el-dialog
      :title="titleTwo"
      :visible.sync="showTwo"
      width="1100px"
      append-to-body
      @close="cancel"
    >
      <el-form
        :model="queryBindTwo"
        ref="queryFormBind"
        :rules="queryBindTwoRules"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="前缀" label-width="50px" prop="codePrefix">
          <el-input
            v-model="queryBindTwo.codePrefix"
            placeholder="请输入前缀"
            clearable
            maxlength="20"
          />
        </el-form-item>

        <el-form-item
          label="后缀起始值"
          label-width="100px"
          prop="codeSuffixStart"
        >
          <el-input
            v-model="queryBindTwo.codeSuffixStart"
            clearable
            placeholder="请输入后缀起始值"
            maxlength="99999999"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleAdd"
            >填充</el-button
          >
          <el-button type="primary" size="mini" @click="handleBindTwo"
            >绑定</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loadingTwo"
        :data="codeTableList"
        width="1000px"
        height="600px"
      >
        <el-table-column label="设备名称" align="center" prop="materialName" />
        <el-table-column label="规格型号" align="center" prop="materialModel" />
        <el-table-column label="设备编码" align="center" prop="maCode" />
        <el-table-column label="出厂编号" align="center" prop="outFacCode">
          <template v-slot:default="{ row }">
            <el-input
              v-model="row.outFacCode"
              placeholder="请输入出厂编码"
              maxlength="30"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="出厂时间" align="center" prop="productDate">
          <template v-slot:default="{ row }">
            <el-date-picker
              v-model="row.productDate"
              type="date"
              placeholder="请输入检验时间"
              style="width: 160px"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-remove"
              @click="handleRemove(scope.$index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
// import {
// } from '@/api/store/newBuy'
import {
  getPurchaseCheckInfo,
  equipmentTypeTree,
  addPurchaseCheckInfo,
  //     getPurchaseCheckInfo,
  updatePurchaseCheckInfo,
} from '@/api/purchase/goodsArrived';

import { getListDetail, getListDetailById,bindAllData } from '@/api/purchase/goodsBind';
// import { getUserByRoleList } from '@/api/system/user'
// import { equipmentTypeTree, supplierInfoList } from '@/api/store/tools'
// import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import HoldingpoleDialog from '@/components/HoldingpoleDialog/index.vue'

// import {} from '@/api/store/newBuy'

export default {
  name: "BindTools",
  dicts: ["sys_normal_disable"],
  // components: { Treeselect, HoldingpoleDialog },
  props: {
    editTaskId: {
      type: [String, Number],
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      taskId: "",
      // isEdit: false,
      // 遮罩层
      loading: false,
      loadingTwo: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      num: 0,
      //机具类型
      equipmentTypeList: [],
      // 角色表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      titleBind: "",
      titleTwo: "",
      // 是否显示弹出层
      open: false,
      showBind: false,
      showTwo: false,
      // 日期范围
      dateRange: [],
      queryBind: {
        pageNum: 1,
        pageSize: 10,
      },
      queryBindTwo: {
        codePrefix: undefined,
        codeSuffixStart: undefined,
      },
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: "",
        supplierId: "",
      },
      maForm: {
        pageNum: 1,
        pageSize: 10,
        taskId:undefined,
      },
      // 表单参数
      form: {},
      materialName: undefined,
      materialModel: undefined,
      codeTableList: [],
      codeTableListTemp: [],
      productDate: undefined,
      taskIdTemp:undefined,
      typeIdTemp:undefined,
      queryBindTwoRules: {
        codePrefix: [
          { required: true, message: "请输入前缀", trigger: "blur" },
        ],
        codeSuffixStart: [
          {
            required: true,
            message: "请输入后缀起始值",
            trigger: "blur",
          },
          {
            pattern: /^[1-9][0-9]*$/,
            message: "请输入大于0且不能以0开头的正整数",
          },
        ],
      },
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          const currentDate = new Date();
          currentDate.setHours(0, 0, 0, 0);
          return time.getTime() < currentDate.getTime();
        },
      };
    },
  },
  watch: {
    // 'maForm.purchaseTime'() {
    //     if (this.maForm.purchaseTime != '') {
    //         // this.maForm.arrivalTime = ''
    //     }
    // },
  },
  mounted() {
    this.taskId = this.editTaskId;
    this.maForm.taskId = this.taskId;
    this.getTaskInfo();
    // this.getUserList()
    // this.getList();
    // this.supplierInfoList()
  },
  methods: {
    /** 新增按钮操作 */
    handleBackAll() {},

    //获取任务详情--- 编辑回显数据
    getTaskInfo() {
      this.maForm.pageNum = 1;
      this.getList();
    },

        //获取任务详情--- 编辑回显数据
    handleQuery() {
      this.maForm.pageNum = 1;
      this.getList();
    },

    getList(){
        this.loading = true;
        getListDetail(this.maForm).then((response) => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      }); 
    },

    //打开查看页面
    handleView(row) {
      this.loadingTwo = true;
      getListDetailById({ taskId: row.taskId, typeId: row.typeId }).then(
        (response) => {
          this.getListBind = response.rows;
          this.showBind = true;
          this.titleBind = "查看";
          this.loadingTwo = false;
        }
      );
    },
    //打开绑定页面
    handleBind(row) {
      this.queryBindTwo = {};
      this.resetForm("queryFormBind");
      this.titleTwo = "绑定";
      this.showTwo = true;
      this.num = row.checkNum;
      this.materialName = row.materialName;
      this.materialModel = row.materialModel;
      this.productDate = row.productDate;
      this.taskIdTemp = row.taskId;
      this.typeIdTemp = row.typeId;
    },

    //填充
    handleAdd() {
      this.$refs["queryFormBind"].validate((valid) => {
        if (valid) {
          this.codeTableList = [];
          // 设备编码: 前缀 拼接 后缀
          for (let i = 0; i < this.num; i++) {
            let suffix = parseInt(this.queryBindTwo.codeSuffixStart) + i;
            suffix = suffix.toString().padStart(5, "0");
            console.log("suffix", suffix);
            // console.log('🚀 ~ fillCodeForm ~ suffix:', suffix);
            suffix = isNaN(suffix) ? "" : suffix;
            console.log("suffixTwo", suffix);
            const maCode = `${this.queryBindTwo.codePrefix || ""}${suffix}`;
            console.log("maCode", maCode);
            // 出厂编码
            const outFacCode = "";
            const materialName = this.materialName;
            const materialModel = this.materialModel;
            const productDate = this.productDate;
            // const productDate = this.queryBindTwo.productDate
            this.codeTableList.push({
              materialName,
              materialModel,
              maCode,
              outFacCode,
              productDate,
            });
          }
        }
      });
    },

    handleBindTwo(){
        this.codeTableList.forEach(item=>{
           this.codeTableListTemp.push({maCode:item.maCode,outFacCode:item.outFacCode,productDate:item.productDate})
        })
            bindAllData({taskId:this.taskIdTemp,typeId:this.typeIdTemp,dtoList:this.codeTableListTemp}).then(
                (response) => {
                   this.$modal.msgSuccess("绑定成功");
                    this.getList();
                    this.showTwo = false
                    
                },
            )
    },

    handleRemove(index){
        this.codeTableList.splice(index,1)
    },
    
    cancel() {
      this.codeTableList = [];
      this.showTwo = false;
      this.reset();
    },
    reset() {
      this.resetForm("queryFormBind");
    },


    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      //   this.form = response.data;
      //   this.open = true;
    },
    /** 明细按钮操作 */
    handleDetail(row) {
      this.holdingpoleData = row;
      this.showDialog = true;
    },

    /** 删除按钮操作 */
    handleBack(row) {
      // console.log(row.id)
      this.$modal
        .confirm("是否确认删除所选择的数据项？")
        .then(() => {
          this.deviceType.forEach((e, index) => {
            if (e[3] === row.typeId) {
              this.deviceType.splice(index, 1);
              this.propsKey++;
            }
          });
          this.equipmentList.forEach((item, index) => {
            if (item.id == row.id) {
              this.equipmentList.splice(index, 1);
            }
          });
        })
        .catch(() => {});

      // const roleIds = row.roleId || this.ids;
      // this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function() {
      //   return delRole(roleIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});
    },
  },
};
</script>
<style lang="scss">
.popper-select {
  .el-cascader-panel .el-scrollbar .el-checkbox {
    display: none;
  }

  .el-cascader-panel .el-scrollbar:nth-child(4) .el-checkbox {
    display: block !important;
  }
}
</style>
