<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="100px">
      <el-row type="flex" justify="end">
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px;margin-top: -5px">
          <el-button
            type="primary"
            @click.native="saveOrder('1')"
            :loading="draftLoading"
          >草稿保存
          </el-button
          >
          <el-button
            type="primary"
            @click.native="saveOrder('2')"
            :loading="submitLoading"
          >提交单据
          </el-button
          >
        </el-button-group>
      </el-row>
      <el-card style="margin-top: -5px;">
        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item prop="billNo" label="领用单号:">
              <el-input v-model="formData.billNo" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="createTime" label="创建时间:">
              <el-date-picker
                :disabled="true"
                v-model="formData.createTime"
                type="datetime"
                placeholder="选择日期"
                style="width: 100%"
                :clearable="false"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="11">
            <el-form-item prop="invCode" label="当前仓库:">
              <el-select v-model="formData.invCode" @change="subStorageChange" placeholder="当前仓库信息"
                         style="width: 100%;"
                         :disabled="codeArray.length>0"
                         clearable>
                <el-option
                  v-for="item in invList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item class="query-form-item" prop="targetInvCode" label="到货仓库:">
              <el-select v-model="formData.targetInvCode" placeholder="请选择到货仓库" @change="getTargerType"
                         clearable="true"
                         style="width: 100%"
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <!--          <el-col :span="11">-->
          <!--            <el-form-item prop="billType" label="领用类型:">-->
          <!--              <el-select v-model="formData.billType" placeholder="请选择领用类型" style="width: 100%"-->
          <!--                         clearable>-->
          <!--                <el-option-->
          <!--                  v-for="item in busTypes"-->
          <!--                  :key="item.originAction"-->
          <!--                  :label="item.originName"-->
          <!--                  :value="item.originAction">-->
          <!--                  <span style="float: left">{{ item.originName }}</span>-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="11">
            <el-form-item prop="remark" label="备注:">
              <el-input v-model="formData.remark" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>

          <el-col v-if="formData.status==4" :span="11">
            <el-form-item prop="remark" label="拒绝原因:">
              <el-input :disabled="true" v-model="formData.auditRemark" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card>
        <el-row>
          <div style="margin: 0px 60px 10px auto; height: 35px;  float: right;">
            <el-button-group>
<!--            <el-button-->
<!--              type="primary"-->
<!--              @click.native.stop="selectWarlockBagFunction()"-->
<!--              :loading="loading"-->
<!--            >术式套包录入-->
<!--            </el-button>-->
            <el-button
              type="primary"
              @click.native.stop="selectProductFunction()"
              :loading="loading"
            >药品录入
            </el-button
            >
            </el-button-group>
          </div>
        </el-row>
        <el-table v-loading="loading" :data="codeArray" style="width: 100%;"
                  :row-class-name="tableRowClassName"
                  border
                  max-height="300" height="300" ref="multipleTable">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="药品标识" prop="nameCode" width="160"></el-table-column>
          <el-table-column label="药品通用名称" prop="cpmctymc" width="180" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="包装规格" prop="bzgg" width="180" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="批次号" prop="batchNo" width="120" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="价格" prop="price" width="100" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="计量单位" prop="measname" show-overflow-tooltip="true" width="100"></el-table-column>
          <el-table-column label="领用数量" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.count"
                        placeholder="请输入数量" style="width: 80%"
                        type='number'
                        @change="tableCountChange(scope.row)"
                        :disabled="scope.row.index !== selectedIndex"
                        oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="批准文号" prop="zczbhhzbapzbh" width="180"></el-table-column>
          <el-table-column label="生产厂家" prop="manufactory" width="180"></el-table-column>
          <el-table-column label="供应商" prop="supName" width="180"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" :disabled="!ischeck || scope.row.index != selectedIndex"
                         @click.stop="true"
                         @click.native="save(scope.row)">保存
              </el-button>
              <el-button type="text" size="small" :disabled="scope.row.index == selectedIndex  ||  ischeck"
                         @click.stop="true"
                         @click.native="rowChange(scope.row)">编辑
              </el-button>
              <el-button type="text" size="small" @click.stop="true"
                         @click.native="deleteCodeArray(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-form>


    <el-dialog
      title="业务详情-术式套包录入"
      :visible.sync="selectWarlockBagVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="85%"
      v-if="selectWarlockBagVisible"
      :append-to-body='true'
    >
      <selectWarlockBag
        :closeDialog="closeDialogC2"
        :data="formData"
        :codeArray="codeArray"
        :type="1"
      ></selectWarlockBag>
    </el-dialog>

    <el-dialog
      title="库存药品物资录入"
      :visible.sync="selectInvProductVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="85%"
      v-if="selectInvProductVisible"
      :append-to-body='true'
    >
      <dialogInvProduct
        :closeDialog="closeDialogC2"
        :invQueryData="formData"
        :codeArray="codeArray"
        :type="1"
      ></dialogInvProduct>
    </el-dialog>
  </div>
</template>

<script>
import {getBusChange} from "@/api/basic/busTypeChange";
import {inserThrOrderWeb, updateReceive, updateReceiveDetail, delReceiveDetail} from "@/api/thrsys/thrOrderReceive";
import {filterSubByInv, findByFrom, findByUp, findInvByUser, findLyInv} from "@/api/system/invSubWarehouse";
import dialogInvProduct from "./DialogSelectInvProduct";
import {addDetail, getOrderDetail, repeatAdd} from "@/api/pharmaceuticals/receiveDrugOrder";
import {parseTime} from "@/utils/coTools";
import {listApplyDetail} from "@/api/purchase/purApply";
import selectWarlockBag from "@/views/basic/destiny/warlockBagModel";

export default {
  name: "idQuery",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    idQuery: {
      type: Object,
      required: true,
    },
    closeConfirmFunction: {
      type: Function,
      required: true,
    },
    editType: {
      type: Object,
      required: true,
    },
    productType: {
      type: Object,
      required: false,
    },
    isRepeat: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      showSearch: true,
      code: "",
      query: {
        orderIdFk: "",
        // page: 1,
        // limit: 10,
      },
      formData: {
        invCode: null,
        targetInvCode: null,

        billNo: null,
        createTime: "",
        billType: "HCLY",
      },
      formRules: {
        createTime: [
          {required: true, message: "请输入创建日期", trigger: "blur"}
        ],
        billType: [
          {required: true, message: "请选择业务类型", trigger: "blur"}
        ],
        invCode: [
          {required: true, message: "请选择当前仓库", trigger: "blur"}
        ],
        targetInvCode: [
          {required: true, message: "请选择往来仓库", trigger: "blur"}
        ],
      },
      codeArray: [],
      invList: [],
      fromStorageOptions: [],
      fromOptions: [],
      total: 0,
      loading: false,
      draftLoading: false,
      submitLoading: false,
      index: null,
      formLoading: false,
      formVisible: false,
      deleteLoading: false,
      orderNo: null,
      statusMap: {
        0: "草稿",
        1: "未审核",
        2: "已审核",
        3: "已拒绝"
      },
      orderEditor: true,
      iCount: 0,
      sOptions: [],
      sValue: [],
      sList: [],
      sLoading: false,
      busTypes: [],
      currentRow: {},
      selectedIndex: null,
      selectInvProductVisible: false,
      selectWarlockBagVisible: false,
      thisData: {},
      storageList: [],
      invQueryData: {},
      type: 1,
      Receive: null,
      ischeck: false,

    };
  },
  components: {
    dialogInvProduct,selectWarlockBag
  },
  methods: {
    //当前分库
    finCurInv() {
      this.invList = [];
      let query = {
        filter: 3
      };
      findInvByUser(query)
        .then((response) => {
          this.invList = response.data || [];
        })
        .catch(() => {
        });
    },
    //往来分库
    findFromInv() {
      let cQuery = {
        locInvCode: this.formData.invCode,
      };
      findLyInv(cQuery)
        .then((response) => {
          this.fromOptions = response.data || [];
          if (this.fromOptions != null && this.fromOptions.length > 0) {
            this.formData.targetInvCode = this.fromOptions[0].code;
          }
        })
        .catch(() => {
        });
    },
    //领用类型
    getBusType() {
      let query = {
        enable: true,
        type: 1,
      };
      getBusChange(query)
        .then((response) => {
          this.busTypes = response.data.list || [];
        })
        .catch(() => {
        });
    },
    hideSearch() {
      this.showSearch = !this.showSearch;
    },
    getTargerType() {
      this.formData.advanceType = this.fromOptions.find(item => item.code == this.formData.targetInvCode).advanceType
      console.log(this.formData)
    },
    saveOrder(status) {
      this.code = "";
      this.$refs.multipleTable.setCurrentRow();
      this.currentRow = {};
      this.selectedIndex = "";
      this.iCount = 0;
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.codeArray.length < 1) {
            this.$message.warning('未添加产品');
            return;
          }

          for (let i = 0; i < this.codeArray.length; i++) {
            if (!this.$isBlank(this.codeArray[i].productDate) && this.codeArray[i].productDate.length != 6) {
              return this.$message.error('生产日期格式错误');
            }
            if (!this.$isBlank(this.codeArray[i].expireDate) && this.codeArray[i].expireDate.length != 6) {
              return this.$message.error('失效日期格式错误');
            }

          }

          if (status === '2') {
            for (let i = 0; i < this.codeArray.length; i++) {
              if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                return this.$message.error('单据数量不能为0');
              }


            }
          }
          if (status === '0') {
            for (let i = 0; i < this.codeArray.length; i++) {
              if (this.$isBlank(this.codeArray[i].count) || this.codeArray[i].count == "0") {
                return this.$message.error('单据数量不能为0');
              }
            }
          }
          if (status == "1"){
            this.draftLoading = true
          }
          if (status == "1") {
            this.submitFunction(status);
          } else {
            let tip = "是否确定提交订单?";
            this.$confirm(tip, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.submitLoading = true
              this.submitFunction(status);
            }).catch(() => {
              this.draftLoading = false
              this.submitLoading = false
            });
          }


        }
      });
    },


    submitFunction(status) {
      let tMessage = status === '501' ? '保存' : '提交';
      let tQuery = this.formData;
      tQuery.status = status;
      tQuery.subErpOrders = this.codeArray;
      tQuery.thirdPartyDate = 2;
      tQuery.productType = this.productType;
      updateReceive(tQuery)
        .then(response => {
          if (status == "1"){
            this.draftLoading = false
          }else {
            this.submitLoading = false
          }
          if (response.code === 20000) {
            this.$message.success(tMessage + "成功");
            this.closeDialog(true);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
            this.draftLoading = false
            this.submitLoading = false
        })
    },
    selectProductFunction(event) {

      if (this.formData.targetInvCode == null) {
        this.$message.error("往来信息为空！");
        return;
      }

      if (this.$isBlank(event)) {
        this.selectInvProductVisible = true;
      }
    },
    closeDialogC2(rData) {
      this.selectInvProductVisible = false;
      this.selectWarlockBagVisible = false;
      this.formData.billNo = rData;
      this.getOrderDetailList();

    },
    selectWarlockBagFunction(event) {

      if (this.formData.targetInvCode == null) {
        this.$message.error("往来信息为空！");
        return;
      }

      if (this.$isBlank(event)) {
        this.selectWarlockBagVisible = true;
      }
    },

    save() {
      if (this.$isNotBlank(this.Receive)) {
        this.Receive.targetInvCode = this.formData.targetInvCode
        this.Receive.advanceType = this.formData.advanceType
        updateReceiveDetail(this.Receive).then(res => {
          if (res.code == 20000) {
            this.loading = false;
            this.ischeck = false;
            this.selectedIndex = null;
            this.getOrderDetailList()
            this.$message.success('修改成功');
          } else {
            this.$message.error(res.message);
          }

        })
      }
    },
    rowChange(val) {

      // if(this.Receive!=null){
      //   this.save()
      // }
      this.Receive = val;
      this.ischeck = true;
      this.currentRow = val;
      this.selectedIndex = val.index;
      this.iCount = val.count;
      // this.focusNext('iCount');

      this.getOrderDetailList()
    },
    tableCountChange(row) {
      this.Receive = row;
    },
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
    },
    focusNext(nextRef) {
      this.$refs[nextRef].focus()
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
        this.getList();
      }
    },
    deleteCodeArray(index, row) {
      let _this = this
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (_this.formData.billNo) {
          _this.detailLoading = true;
          if (_this.$isNotBlank(row.id)) {
            delReceiveDetail({id: row.id})
              .then(response => {
                _this.detailLoading = false;
                if (response.code === 20000) {
                  _this.getOrderDetailList();
                } else {
                  _this.$message.error(response.message);
                }
              })
              .catch(() => {
                _this.detailLoading = false;
              })
          } else {
            _this.$message.success('删除成功');
            _this.codeArray.splice(index, 1);
          }
        } else {
          _this.$message.success('删除成功');
          _this.codeArray.splice(index, 1);
        }
      }).catch(() => {

      });
    },
    subStorageChange(item) {
      this.formData.targetInvCode = '';
      this.getBusType();
      this.findFromInv();
    },

    getOrderDetailList() {
      this.loading = true;
      this.query.orderIdFk = this.formData.billNo;
      getOrderDetail(this.query) //查找该单号下的所有条码
        .then((response) => {
          this.codeArray = response.data.list || [];
          this.total = response.data.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },


    getDetailByRepeat(value) {
      this.query = {
        orderIdFk: value
      }
      getOrderDetail(this.query) //查找该单号下的所有条码
        .then((response) => {
          this.codeArray = response.data.list || [];
          this.total = response.data.total || 0;
          this.loading = false;
          this.codeArray.forEach(item => {
            item.orderIdFk = this.pId
          })

        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });

    }
  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    if (this.$isNotBlank(this.idQuery.id)) {
      this.editType = true;
      this.query.limit = 100;
      this.query.orderIdFk = this.idQuery.id;
      this.formData = this.idQuery.formData;
      this.orderEditor = true;
      this.sValue = this.formData.corpName;
      this.getOrderDetailList();
    } else {
      this.editType = false;
      let date = new Date();
      if (this.isRepeat) {
        this.formData = this.idQuery.formData;
        let query = {
          orderIdFk: this.formData.billNo
        }
        getOrderDetail(query) //查找该单号下的所有条码
          .then((response) => {
            let codeArray = response.data.list || [];
            this.loading = false;
            let repeatQuery = {
              purReceiveEntity: this.formData,
              datas: codeArray
            }
            repeatAdd(repeatQuery).then((response) => {
              this.loading = false;
              if (response.code === 20000) {
                this.formData = response.data;
                this.getOrderDetailList()
              } else {
                this.$message.error(response.message);
              }
            }).catch(() => {
              this.loading = false;
            });
            // codeArray.forEach(item => {
            //
            // })
          })
          .catch(() => {
            this.loading = false;
            this.list = [];
            this.total = 0;
          });


      } else {
        this.formData = {
          invCode: this.$store.getters.locInvCode,
          targetInvCode: null,
          billType: "HCLY",
          billNo: null,
          createTime: parseTime(
            date,
            "{y}-{m}-{d} {h}:{i}:{s}"
          ),
        };
        this.orderEditor = false;
      }
    }

    this.getBusType();
    this.findFromInv();
    this.finCurInv();
  },
};
</script>
<style scoped>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



