<template>
  <div>
    <el-form :model="formData" :rules="formRules" ref="dataForm" label-width="120px">
      <el-row type="flex" justify="end">
        <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
          <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>
          <el-col :span="11">
            <el-form-item label="采购单号:" prop="billNo">
              <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 label="创建时间:" prop="createTime">
              <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 style="margin-top: -10px">
          <el-col :span="11">
            <el-form-item label="紧急程度:" prop="emergency">
              <el-select v-model="formData.emergency" placeholder="请选择紧急程度" style="width: 100%" clearable>
                <el-option label="正常" :value=1></el-option>
                <el-option label="较急" :value=2></el-option>
                <el-option label="特急" :value=3></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="到货截止:" prop="arrivalTime">
              <el-date-picker
                v-model="formData.arrivalTime"
                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>
          <el-col :span="11">
            <el-form-item label="采购仓库:" prop="invCode">
              <el-select v-model="formData.invCode" @change="setDeptCode" placeholder="采购仓库信息" style="width: 100%"
                         clearable>
                <el-option
                  v-for="item in invCodeList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.code">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.warehouseName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item
              prop="supId"
              label="供应商:"
            >
              <el-select
                v-model="formData.supId"
                filterable
                remote
                :disabled="corpOrderIdDisabled"
                clearable
                reserve-keyword
                style="width: 90%"
                placeholder="请选择供应商"
                :remote-method="findMethod"
              >
                <el-option
                  v-for="item in fromOptions"
                  :key="item.erpId"
                  :label="item.name"
                  :value="item.erpId"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="采购说明:" prop="remark">
              <el-input v-model="formData.remark" auto-complete="off" type="textarea" autosize></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11" v-show="formData.status==4">
            <el-form-item label="拒绝原因:">
              <el-input v-model="formData.auditRemark" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

      </el-card>


      <el-card>
        <el-row type="flex" justify="end">
          <el-button-group style="display: flex">
            <el-button-group style="display: flex;margin-bottom: 15px; margin-right: 50px">
<!--              <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 type="primary" :loading="loading" @click.native.stop="selectApply()">选入采购单</el-button>-->
            </el-button-group>


          </el-button-group>
        </el-row>
        <el-table v-loading="loading" :data="codeArray" style="width: 100%;" :row-class-name="tableRowClassName" border
                  highlight-current-row max-height="300" height="300" ref="multipleTable">
          <el-table-column label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="药品标识" prop="nameCode"></el-table-column>
          <el-table-column label="药品名称" prop="productName" show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="规格型号" prop="spec" 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="价格" prop="price" show-overflow-tooltip="true" width="100"></el-table-column>
          <el-table-column width="150" label="采购数量">
            <template slot-scope="scope">
              <el-input size="small" v-model="scope.row.count"
                        placeholder="请输入数量" style="width: 80%"
                        type='number'
                        :disabled="scope.row.index !== selectedIndex"
                        oninput="value=value.replace(/[^\d]/g,'')"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="批准文号" prop="zczbhhzbapzbh"></el-table-column>
          <el-table-column label="生产厂家" prop="manufactory"></el-table-column>
          <el-table-column label="供应商" prop="supName">
            <template slot-scope="scope">
              <el-select size="mini"
                         v-model="scope.row.supName" clearable
                         :disabled="scope.row.index !== selectedIndex"
                         placeholder="请选择">
                <el-option v-for="item in suppliers"
                           :key="item.erpId"
                           :label="item.name"
                           :value="item.name">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" size="small" :disabled="scope.row.index === selectedIndex" @click.stop="true"
                         @click.native="rowChange(scope.row)">编辑
              </el-button>
              <el-button type="text" size="small" :disabled="scope.row.index !== selectedIndex" @click.stop="true"
                         @click.native="tableCountChange(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="thisData"
        :codeArray="codeArray"
        :pId="pId"
        :type="5"
      ></selectWarlockBag>
    </el-dialog>
    <el-dialog
      title="药品录入"
      :visible.sync="selectProductVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="80%"
      v-if="selectProductVisible"
      :append-to-body='true'
    >
      <purOrderProducts
        :closeDialog="closeDialogC2"
        :purType="1"
        :pId="pId"
        :supId="formData.supId"
        :data="thisData"
      ></purOrderProducts>
    </el-dialog>

    <el-dialog
      title="采购计划单据选入"
      :visible.sync="selectApplyVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="80%"
      append-to-body
      v-if="selectApplyVisible"
    >
      <select-plan-list-dialog
        :data="thisData"
        :pId="pId"
        :closeDialog="closeDialogC2"
      ></select-plan-list-dialog>
    </el-dialog>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import purOrderProducts from "@/views/pharmaceuticals/purOderDrug/purOrderSelectProduct";
import {
  inserThrOrderWeb,
  delOrderDetail,
  listOrderDetail,
  addOrderId,
  selectOrderDetail,
  updateDetail,
  filterSupList
} from "@/api/pharmaceuticals/purOrderDrug";
import {filterSubByInv} from "@/api/system/invSubWarehouse";
import SelectPlanListDialog from "@/views/pharmaceuticals/purPlanDrug/selectPlanListDialog";
import {parseTime} from "@/utils/coTools";
import {getBasicUnitMaintains} from "@/api/basic/basicUnitMaintain";
import selectWarlockBag from "@/views/basic/destiny/warlockBagModel";

export default {
  name: "idQuery",
  props: {
    pageType: {
      type: Object,
      required: true,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    idQuery: {
      type: Object,
      required: true,
    },
    isChang: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      code: "",
      query: {
        orderIdFk: "",
        page: 1,
        limit: 10,
      },
      formData: {
        id: null,
        billNo: null,
        createTime: "",
        remark: "",
        billType: "CGDD",
        deptCode: null,
        locStorageCode: null,
        invWarehouseCode: null,
        supId: null,
        pageType: null,
      },
      pId: null,
      formRules: {},
      fromOptions: [],
      codeArray: [],
      total: 0,
      loading: false,
      draftLoading: false,
      submitLoading: false,
      index: null,
      formLoading: false,
      formVisible: false,
      deleteLoading: false,
      orderNo: null,
      suppliers: [],
      statusMap: {
        1: "草稿",
        2: "未审核",
        3: "已审核",
      },
      typeMap: {
        1: "预入库",
        2: "普通采购",
      },
      orderEditor: true,
      sOptions: [],
      sValue: [],
      sList: [],
      sLoading: false,
      busTypes: [],
      currentRow: {},
      selectedIndex: "",
      selectProductVisible: false,
      selectWarlockBagVisible: false,
      thisData: {},
      storageList: [],
      invCodeList: [],
      invQueryData: {},
      selectApplyVisible: false,
      corpOrderIdDisabled: false,

    };
  },
  watch: {
    isChang: function () {
      this.$emit("cancelDialog", this.pId);
    },
  },
  components: {
    draggable,
    purOrderProducts,
    SelectPlanListDialog,
    selectWarlockBag
  },
  methods: {
    saveOrder(status) {

      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.codeArray.length < 1) {
            this.$message.warning('未添加药品');
            return;
          }
          if (status === '2') {
            if (this.formData.createTime == "" || this.formData.createTime == null) {
              return this.$message.error("单据日期不能为空！");
            }
            // if (this.formData.billType == "" || this.formData.billType == null) {
            //     return this.$message.error("采购类型不能为空！");
            // }
            if (this.formData.invCode == "" || this.formData.invCode == null) {
              return this.$message.error("采购仓库不能为空！");
            }
            if (this.formData.emergency == "" || this.formData.emergency == null) {
              return this.$message.error("紧急程度不能为空！");
            }
            if (this.formData.arrivalTime == "" || this.formData.arrivalTime == null) {
              return this.$message.error("到货时间不能为空！");
            }
            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 (this.$isBlank(this.codeArray[i].supName)) {
                return this.$message.error('请选择药品对应供应商');
              }
            }
          }
          if (status == "1") {
            if (this.formData.createTime == "" || this.formData.createTime == null) {
              return this.$message.error("单据日期不能为空！");
            }
            if (this.formData.invCode == "" || this.formData.invCode == null) {
              return this.$message.error("采购仓库不能为空！");
            }
            if (this.formData.emergency == "" || this.formData.emergency == null) {
              return this.$message.error("紧急程度不能为空！");
            }
            if (this.formData.arrivalTime == "" || this.formData.arrivalTime == null) {
              return this.$message.error("到货时间不能为空！");
            }
            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 (this.$isBlank(this.codeArray[i].supName)) {
                return this.$message.error('请选择药品对应供应商');
              }
            }

            this.submitFunction(status);
          } else {
            let tip = "是否确定提交订单?";
            this.$confirm(tip, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.submitLoading = true
              this.submitFunction(status);
            }).catch(() => {
              if (status == '1'){
                this.draftLoading = false
              }else {
                this.submitLoading = false
              }
            });
          }
        }
      });
    },
    submitFunction(status) {
      let tMessage = status === '1' ? '保存' : '提交';
      this.loading = true;
      this.formData.id = this.pId;
      this.formData.pageType = this.pageType
      this.formData.productType = 2
      let tQuery = {
        editStatus: status,
        purOrderEntity: this.formData,
        subErpOrders: this.codeArray,
        type: 1,
      }
      if (status == '1'){
        this.draftLoading = true
      }
      inserThrOrderWeb(tQuery)
        .then(response => {
          if (status == '1'){
            this.draftLoading = false
          }else {
            this.submitLoading = false
          }
          // this.loading = false;
          if (response.code === 20000) {
            this.$message.success(tMessage + "成功");
            this.closeDialog(true);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(() => {
          if (status == '1'){
            this.draftLoading = false
          }else {
            this.submitLoading = false
          }
        })
    },
    selectProductFunction() {
      this.selectProductVisible = true;
      //当父id为空的时候生成id
      if (this.pId == null) {
        addOrderId().then(response => {
          if (response.code === 20000) {
            this.pId = response.data
          }
        }).catch(() => {
          this.loading = false;
        })
      }
      this.thisData.stockOrderLists = this.codeArray;
    },
    selectWarlockBagFunction() {
      this.selectWarlockBagVisible = true;
      //当父id为空的时候生成id
      if (this.pId == null) {
        addOrderId().then(response => {
          if (response.code === 20000) {
            this.pId = response.data
          }
        }).catch(() => {
          this.loading = false;
        })
      }
      this.thisData.stockOrderLists = this.codeArray;
    },
    setDeptCode(obj) {
      this.formData.deptCode = this.invCodeList.find(item => item.code == obj).parentId;
    },
    closeDialogC2() {
      this.selectProductVisible = false;
      this.selectWarlockBagVisible = false;
      this.selectApplyVisible = false;
      this.query = {
        orderIdFk: this.pId
      }
      selectOrderDetail(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;
        });
    },
    rowChange(val) {
      if (this.currentRow != null){
        updateDetail(this.currentRow);
      }
      this.currentRow = val;
      this.selectedIndex = val.index;
      filterSupList({productId: val.productId}) //查找该单号下的所有条码
        .then((response) => {
          this.suppliers = response.data || [];
        })
        .catch(() => {

        });
    },
    tableCountChange(row) {
      if (this.$isNotBlank(row)) {
        this.currentRow.supId= this.suppliers.find(item => item.name == row.supName).erpId
        updateDetail(this.currentRow);
        this.selectedIndex = ""
      }
    },
    tableRowClassName({row, rowIndex}) {
      row.index = rowIndex;
    },
    // 刷新表单
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
        this.getList();
      }
    },
    deleteCodeArray(index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$refs.multipleTable.setCurrentRow();
        this.currentRow = {};
        this.selectedIndex = "";

        if (this.orderEditor) {
          this.detailLoading = true;
          if (this.$isNotBlank(row.id)) {
            let delIds = [];
            delIds.push(row.id)
            delOrderDetail(delIds)
              .then(response => {
                this.detailLoading = false;
                if (response.code === 20000) {
                  this.$message.success(response.data);
                  // this.getStockOrderDetailList();
                  this.codeArray.splice(index, 1);
                } 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(() => {

      });
    },
    getStockOrderDetailList() {
      this.loading = true;
      listOrderDetail(this.query) //查找该单号下的所有条码
        .then((response) => {
          console.log(response)
          this.codeArray = response.data.list || [];
          this.total = response.data.total || 0;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.list = [];
          this.total = 0;
        });
    },
    findSubInvs() {
      this.invCodeList = [];
      let query = {
        filter: 3
      };
      filterSubByInv(query)
        .then((response) => {
          this.invCodeList = response.data || [];
          if (this.invCodeList != null && this.invCodeList.length == 1) {
            this.formData.invCode = this.invCodeList[0].code;
          }
        })
        .catch(() => {
        });
    },
    selectApply() {
      this.selectApplyVisible = true;
      //当父id为空的时候生成id
      if (this.pId == null) {
        addOrderId().then(response => {
          if (response.code === 20000) {
            this.pId = response.data
          }
        }).catch(() => {
          this.loading = false;
        })
      }
    },


    //获取往来单位候选列表
    findMethod(query) {
      this.fromOptions = [];
      let cQuery = {
        key: query,
        corpType: 2,
        outType: null,
        page: 1,
        limit: 20,
      };
      getBasicUnitMaintains(cQuery)
        .then((response) => {
          this.loading = false;
          this.fromOptions = response.data.list || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },

  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {

    if (this.$isNotBlank(this.idQuery.id)) {
      this.query.limit = 100;
      this.pId = this.idQuery.id;
      this.query.orderIdFk = this.idQuery.id;
      this.formData = this.idQuery.formData;
      this.orderEditor = true;
      this.sValue = this.formData.corpName;
      this.findMethod(this.formData.supId);
      this.getStockOrderDetailList();
    } else {
      var date = new Date();
      this.formData = {
        id: null,
        billNo: null,
        remark: "",
        billType: "CGDD",
        deptCode: null,
        incCode: null,
        createTime: parseTime(
          date,
          "{y}-{m}-{d} {h}:{i}:{s}"
        ),
      };
      this.orderEditor = false;
    }
    this.findSubInvs();
    this.codeArray = [];
  },
};
</script>
<style scoped>

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

</style>



