<template>
  <!-- 新增工机具 -->
  <div>
        <div class="info" style="margin-top: 10px; display: flex; flex-wrap: wrap;margin-left: 10px;" >
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>领用单位：</span>
            {{ leaseApplyData.leaseUnit }}
          </div>
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>领用工程：</span>
            {{ leaseApplyData.leaseProject }}
          </div>
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>联系人：</span>
            {{ leaseApplyData.leasePerson }}
          </div>
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>联系电话：</span>
            {{ leaseApplyData.phone }}
          </div>
        </div>

        <div class="info" style="margin-top: 10px;margin-bottom:10px; display: flex; flex-wrap: wrap;margin-left: 10px" >
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>供货时间：</span>
            {{ leaseApplyData.supplierTime }}
          </div>
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>供货地点：</span>
            {{ leaseApplyData.supplierPlace }}
          </div>
          <div class="item" style="width: 25%;flex-shrink: 0;margin-bottom: 5px;font-size: 14px;">
            <span>业务单号：</span>
            {{ leaseApplyData.code }}
          </div>
        </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleSend"
          >发布</el-button
        >
<!--        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出数据</el-button
        >-->
      </el-col>
      <!-- <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-if="isEdit">导出</el-button>
            </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="leaseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" :selectable="(row) => row.pendingNum != 0 && (row.storageNum-row.pendingOutNum>=row.num)" />
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column
        align="center"
        label="类型名称"
        prop="maTypeName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="规格型号"
        prop="typeName"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="计量单位" prop="unitName" />
      <el-table-column align="center" label="需求数量" prop="preNum" />
      <el-table-column align="center" label="当前库存" prop="storageNum" />
      <el-table-column align="center" label="待出库数量" prop="pendingOutNum" />
      <el-table-column align="center" label="已发布数量" prop="publishNum" :show-overflow-tooltip="true"/>
      <el-table-column align="center" label="已供应数量" prop="outNum" :show-overflow-tooltip="true"/>
      <el-table-column align="center" label="待发布数量" prop="pendingNum" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.pendingNum!== 0? 'red' : 'green' }">
            {{ scope.row.pendingNum }}
          </span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="本次领料数量" prop="num" :show-overflow-tooltip="true" width="150px">
          <template v-slot="scope">
          <el-input
              v-model.number="scope.row.num"
              controls-position="right" type="number"
              v-if="scope.row.pendingNum!=0"
              style="width: 100%"
              :min="0"  @change="handleChange(scope.row)"
           ></el-input>
        </template>
       </el-table-column>
       <el-table-column align="center" label="本次规格型号" prop="newTypeId" width="150px">
         <template slot-scope="scope">
          <el-select
            v-model="scope.row.newTypeId"
            placeholder="请选择规格型号"
            style="width: 100%"
            :key="scope.$index"
            @change="handleChangeType(scope.row)"
          >
            <el-option
              v-for="option in scope.row.typeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            >
            </el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>

      <!-- 发料弹窗-->
    <el-dialog
      :title="title"
      :visible.sync="openView"
      width="600px"
      append-to-body
      @close="closeView"
      v-loading="loading"
    >
      <el-form ref="maForm" :model="maForm" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="领用工程" prop="projectName">
              <el-input v-model="maForm.projectName" placeholder="请输入领用工程" readonly style="width: 240px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="领用单位" prop="unitId">
              <treeselect
                v-model="maForm.unitId"
                :options="uniteList"
                :normalizer="normalizer"
                :show-count="true"
                style="width: 240px"
                :disable-branch-nodes="true"
                noChildrenText="没有数据了"
                noOptionsText="没有数据"
                noResultsText="没有搜索结果"
                placeholder="请选择领用单位"
                @select="uniteChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button
              type="success"
              @click="handleSign"
              >去签协议</el-button>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="24">
          <el-col :span="16">
            <el-form-item label="领用数量" prop="num">
              <el-input
                v-model="maForm.num"
                type="number"
                min="1"
                placeholder="请输入领用数量"
                maxlength="10"
                style="width: 240px"
                @change="handleChange"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <span style="display: inline-block; vertical-align: middle; line-height: 32px;">剩余需求量: {{numTemp}}</span>
          </el-col>
        </el-row> -->
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="领料人" prop="leasePerson">
              <el-input
                v-if="leasePersonList.length === 0"
                v-model="maForm.leasePerson"
                placeholder="请输入领料人"
                maxlength="10"
                style="width: 240px"
              >
              </el-input>
              <el-select
                v-else
                v-model="maForm.leasePerson"
                placeholder="请选择领料人"
                style="width: 240px"
                filterable
              >
                <el-option
                  v-for="(item, index) in leasePersonList"
                  :key="index"
                  :label="item.leasePerson"
                  :value="item.leasePerson"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="maForm.phone"
                placeholder="请输入联系电话"
                maxlength="11"
                style="width: 240px"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getApplyInfo,getTypeOptions,applySubmit
} from "@/api/leasePublish/index";
import { getUnitListLeaseApi, getListLeasePersonApi,getPendingOutNumByTypeId } from '@/api/lease/apply'
import { getAgreement,} from "@/api/lease/apply";
import { getToken } from "@/utils/auth";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: "AddTools",
  components: { Treeselect },
  props: {
    isEdit: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    editTaskId: {
      type: [String, Number],
      default: () => {
        return "";
      },
    },
    editId: {
      type: [String, Number],
      default: () => {
        return "";
      },
    },
  },
  data() {
    return {
      isSubmit: false,
      taskId: "",
      // isEdit: false,
      // 遮罩层
      loading: false,
      loadingTwo: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectTreeProps: {
        children: "children",
        label: "name",
        // multiple: false,
        value: "id",
        // multiple: true,
      },
      uniteList: [],
      // 角色表格数据
      leaseList: [],
      // 弹出层标题
      title: "",
      rowData: {},
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: "",
      },
      maForm: {
        projectName: undefined,
        unitId: undefined,
        num: "",
        leasePerson: "",
        phone: "",
      },
      leasePersonList: [],
      //上层信息
      leaseApplyData: {},
      openView: false,
      // 表单参数
      form: {},
      //剩余需求量
      numTemp: 0,

      items: [],

      isSafeType: 0,

      // 表单校验
      rules: {
        unitId: [
          {
            required: true,
            message: '请选择领用单位',
            trigger: 'blur'
          }
        ],
        leasePerson: [
          {
            required: true,
            message: '请输入领料人',
            trigger: 'change'
          }
        ],
        phone: [
          // { required: true, message: '联系电话不能为空', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],

      },

    };
  },
  computed: {
  },
  mounted() {
    if (this.isEdit) {
      console.log("isEdit", this.isEdit);
      this.taskId = this.editTaskId;
      this.id = this.editId;
      this.getTaskInfo();
    }
  },
  methods: {
    uniteChange(e) {
      this.getLeasePersonList(e.id)
      this.getAgreementId(e.id)
    },
    // 获取领料人列表
    async getLeasePersonList(teamId) {
      try {
        const res = await getListLeasePersonApi({ leaseId: this.id, teamId})
        this.leasePersonList = res.data || []
        if (this.leasePersonList.length == 0) this.maForm.leasePerson = ''
      } catch (error) {
        console.log('🚀 ~ 获取领料人列表失败 ~ error:', error)
      }
    },
    //获取协议
    async getAgreementId(teamId) {
        await getAgreement({
              unitId: teamId,
              projectId: this.leaseApplyData.leaseProjectId,
        }).then((response) => {
          this.isSafeType = response.data.isSafeType;
        });
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    /** 选择单位 */
    async getUnit(){
        getUnitListLeaseApi({ projectId: this.leaseApplyData.leaseProjectId, leaseId: this.id }).then(response => {
          this.uniteList = response.data
        })
    },

    //获取任务详情--- 编辑回显数据
    async getTaskInfo() {
      this.loading = true;
      try {
        const response = await getApplyInfo({ id: this.id });
        this.leaseList = response.data.leaseApplyDetailsList;
        this.leaseApplyData = response.data.leaseApplyInfo;

        for (const item of this.leaseList) {
          this.$set(item, 'num', item.pendingNum);
           this.$set(item, 'newTypeId', item.typeId);

          const optionsResponse = await getTypeOptions({ typeId: item.thirdTypeId });
          const typeOptions = optionsResponse.data.map((type) => ({
            value: type.typeId,
            label: type.typeName,
          }));
          this.$set(item, 'typeOptions', typeOptions);
          console.log("xxxxxxxxxxxxxxxxxxxxxx", item.typeOptions);
        }
      } catch (error) {
        console.error("获取任务信息失败:", error);
      } finally {
        this.loading = false;
        this.$forceUpdate(); // 强制刷新组件
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.items = [];
      this.ids = selection.map((item) => item.id);
      this.items = selection.map((item) => ({'id':item.id,'typeId': item.typeId,'parentId':item.parentId, 'num': item.num, 'newTypeId': item.newTypeId}));
      console.log("yyyyyyyyyyyyy", this.items)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 发料按钮操作 */
   async handleSend(row) {
      // this.numTemp = row.preNum-row.publishNum;
      if(this.ids.length == 0){
        this.$message.error('请选择要发布的数据')
        return
      }
      this.title = "新增发布";
      this.maForm.projectName = this.leaseApplyData.leaseProject
      await this.getUnit();
      this.openView = true;

    },

    handleChange(row){
      if(row.num > row.pendingNum){
        this.$message.error('领料数量不能大于待发布数量')
        this.$set(row, 'num', row.pendingNum)
        return
      }
      if(row.num > (row.storageNum-row.pendingOutNum)){
        const excessNum = row.storageNum - row.pendingOutNum;
        this.$message.error(`领料数量不能大于剩余可出库数量${excessNum}`);
        this.$set(row, 'num', row.pendingNum)
        return
      }


      if (row.num < 1) {
        this.$set(row, 'num', 1)
      }
    },


    //规格型号切换
    async handleChangeType(row) {
      console.log("xxxxxxxx",row.newTypeId)
      // 获取选中的规格型号名称
      const selectedOption = row.typeOptions.find(option => option.value === row.newTypeId);
      if (selectedOption) {
        this.$set(row, 'newTypeName', selectedOption.label);
      }
      const res =  await getPendingOutNumByTypeId(row.newTypeId)
       console.log('yyyyyyyyy',res.data)
      if(res.code==200){
        console.log('yyyyyyyyy',res.data.pendingOutNum)
        console.log('storageNum---',res.data.storageNum)
        this.$set(row, 'pendingOutNum', res.data.pendingOutNum)
        this.$set(row, 'storageNum', res.data.storageNum)
        this.$set(row, 'jiJuType', res.data.jiJuType)
      }
      // this.$set(row, 'newTypeId', row.newTypeId)
      // this.$set(row, 'num', row.num)
    },

    handleSign(){
        this.closeView()
        this.$router.push({ path: '/lease/protocol' })
    },

    submitForm() {
      this.$refs.maForm.validate((valid) => {
        if (valid) {
            let leaseApplyInfo = {
              unitId: this.maForm.unitId,
              leasePerson: this.maForm.leasePerson,
              phone: this.maForm.phone,
              taskId:this.leaseApplyData.taskId,
              projectId: this.leaseApplyData.leaseProjectId,
            }
            let itemsTemp = [];
            this.leaseList.forEach((item) => {
              // 检查 item 的 id 是否存在于 this.items 中
              if (this.items.some((selectedItem) => selectedItem.id === item.id)) {
                console.log('hhhhhhhhhxxxxx',item,this.isSafeType)
                 if(item.jiJuType == 1 && this.isSafeType == 1){
                        this.$modal.msgError("所选择的领用单位的安全工器具协议下所勾选的物资包含机具，不能发布！");
                        return true;
                  }
                // 如果存在，将 item 存入 itemsTemp
                itemsTemp.push({
                  'typeId': item.typeId,
                  'parentId': item.parentId,
                  'num': item.num,
                  'newTypeId': item.newTypeId,
                  'maTypeName': item.maTypeName,
                  'unitName': item.unitName,
                  'typeName': item.newTypeName || item.typeName
                });
              }
            });
            // 检查本次领料数据中是否包含待发布数量为0的数据
            let errorInfo = '';
            itemsTemp.some(item=>{
              if(item.num === 0){
                  errorInfo = "发布数据中含有待发布数量为0的数据，请仔细检查";
                  return true;
              }
            })
            if(errorInfo){
              return this.$modal.msgError(errorInfo);
            }
            console.log("xxxxxxxxxxxxxxxxxxxxxx", itemsTemp)
            if (this.isSubmit) return
            this.isSubmit = true
            this.loading = true
            applySubmit({
            leaseApplyDetailsList: itemsTemp,
            leaseApplyInfo: leaseApplyInfo,
            }).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("发布成功");
              // this.$tab.closeOpenPage({
              //     path: '/store/newBuy/newDevicesList',
              // })

              this.$emit("addToolsSuccess");
            }
            this.loading = false;
            this.isSubmit = false
          }).catch(() => {
            this.loading = false
            this.isSubmit = false
          })
        }

      })
    },

    cancel() {
      this.numTemp = 0;
      this.$refs.maForm.resetFields();
      this.openView = false;
    },

    closeView() {
      this.numTemp = 0;
      this.$refs.maForm.resetFields();
      this.openView = false;
    },

    /** 导出按钮操作 */
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/purchase_check_info/exportDetails",
        { taskId: this.taskId },
        `新购到货详情_${currentTime}.xlsx`
      );
    },



  },

};
</script>
<style lang="scss" scoped>

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.el-icon-arrow-down.is-reverse {
  transform: rotateZ(180deg);
}

</style>
