<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入调价单号"
              clearable
              size="small"
              style="width:160px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="" prop="state">
            <el-select
              style="width:160px"
              v-model="queryParams.state"
              placeholder="请选择单据状态"
              clearable
              size="small"
            >
              <el-option
                v-for="item in billOptions"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictLabel"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="keepingTime">
            <el-date-picker
              style="width:260px"
              clearable
              size="small"
              v-model="queryParams.keepingTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="调价开始时间"
              end-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-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['drugs:TrimPrice:add']"
              >新增</el-button
            >
          </el-form-item>
        </div>
      </div>
    </el-form>

    <el-table
      v-loading="loading"
      :data="TrimPriceList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="调价单号" align="center" prop="code" />
      <el-table-column label="调价方式" align="center" prop="modifyMode">
        <template slot-scope="scope">
          <dict-tag :options="modifyModeArr" :value="scope.row.modifyMode" />
        </template>
      </el-table-column>
      <el-table-column label="调价文号" align="center" prop="modifyNumber" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="billOptions" :value="scope.row.state"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="调价类型" align="center" prop="modifyType">
        <template slot-scope="scope">
          <dict-tag :options="modifyTypeArr" :value="scope.row.modifyType" />
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="createBy" />
      <el-table-column label="制单时间" align="center" prop="createTime" />
      <el-table-column label="记账人" align="center" prop="keepingBy" />
      <el-table-column
        label="记账时间"
        align="center"
        prop="keepingTime"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(1, scope.row)"
            v-hasPermi="['inventory:modifyPrice:edit']"
            v-if="scope.row.state == 1"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            v-hasPermi="['inventory:modifyPrice:edit']"
            @click="handleUpdate(3, scope.row)"
            >详情</el-button
          >
          <!-- scope.row.modifyType !== '2' -->
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            v-hasPermi="['inventory:modifyPrice:edit']"
            @click="handleUpdate(2, scope.row)"
            v-if="scope.row.state == 1"
            >记账</el-button
          >
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleDelete(scope.row)"
            v-if="scope.row.state == 1"
            v-hasPermi="['inventory:modifyPrice:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改统一调价对话框 -->
    <el-dialog
      :fullscreen="true"
      :title="title"
      :visible.sync="open"
      width="1180px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="调价单号">{{form.code}}</el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="调价方式" prop="modifyMode" required>
              <el-select
                v-model="form.modifyMode"
                placeholder="请选择调价方式"
                :disabled="disableDetails"
              >
                <el-option
                  v-for="item in modifyModeArr"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="调价文号" prop="modifyNumber">
              <el-input
                v-model="form.modifyNumber"
                placeholder="请输入调价文号"
                :disabled="disableDetails"
                style="100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="调价类型" prop="modifyType">
              <el-select
                v-model="form.modifyType"
                placeholder="请选择调价类型"
                :disabled="disableDetails"
              >
                <el-option
                  v-for="item in modifyTypeArr"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="制单人" prop="createBy">
              <el-input v-if="form.createBy" v-model="form.createBy" disabled style="width: 100%"></el-input>
              <el-input v-else :value="createBy" disabled style="width: 100%"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="制单时间" prop="createTime">
              <el-input v-if="form.createTime" v-model="form.createTime" disabled style="width: 100%"></el-input>
              <el-input v-else v-model="createTime" disabled style="width: 100%"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="记账人" prop="keepingBy">
              <el-input v-if="form.keepingBy" v-model="form.keepingBy" disabled style="width: 100%"></el-input>
              <template v-else>
                <el-input v-if="BtnState==2" :value="createBy" disabled style="width: 100%"></el-input>
                <el-input v-else value="" disabled style="width: 100%"></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="记账时间" prop="keepingTime">
              <el-input v-if="form.keepingTime" v-model="form.keepingTime" disabled style="width: 100%"></el-input>
              <template v-else>
                <el-input v-if="BtnState==2" :value="createTime" disabled style="width: 100%"></el-input>
                <el-input v-else value="" disabled style="width: 100%"></el-input>
              </template>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                placeholder="请输入备注"
                :disabled="disableDetails"
                style="100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider content-position="center">统一调价详情信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            v-if="!disableDetails"
            @click="handleAddModifyPriceDetails"
            >添加</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            v-if="!disableDetails"
            @click="handleDeleteModifyPriceDetails"
            >删除</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="trimPriceDetails"
        :row-class-name="rowWarehouseDetailIndex"
        @selection-change="handleWarehouseDetailSelectionChange"
        ref="warehouseDetail"
        border
        :summary-method="getSummaries"
        show-summary
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column label="序号" align="center" prop="index" width="65" />
        <el-table-column
          label="药品名称"
          prop="drugsName"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <selectTable v-if="open" :index="scope.$index" :info="scope.row" :disableDetails="disableDetails" @selectChange="selectChange"></selectTable>
          </template>
        </el-table-column>
        <el-table-column
          label="药品类型"
          prop="drugsType"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.drugsType">{{drugsTypeOptions.find(v=>v.dictValue==scope.row.drugsType).dictLabel}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="药品规格"
          prop="specsName"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.row.specsName}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="药品产地"
          prop="priceName"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.row.priceName}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="药品单位"
          prop="packingUnit"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <dict-tag v-if="scope.row.packingUnit" :options="unitArr" :value="scope.row.packingUnit" />
          </template>
        </el-table-column>

        <el-table-column
          label="调价数量"
          prop="stock"
          align="center"
          width="110"
        ></el-table-column>
        <el-table-column
          label="加价率"
          prop="markupRate"
          align="center"
          width="110"
        >
          <template slot-scope="scope">{{scope.row.markupRate}}</template>
        </el-table-column>
        <el-table-column
          label="原进货单价"
          prop="oldPurchasePrice"
          align="center"
          width="110"
        ></el-table-column>
        <el-table-column
          label="现进货单价"
          prop="purchasePrice"
          align="center"
          width="110"
        ></el-table-column>

        <el-table-column
          label="原进货总价"
          prop="purchasePriceAll"
          align="center"
          width="110"
        >
          <template slot-scope="scope">
            <div>{{scope.row.stock? (scope.row.stock * scope.row.oldPurchasePrice).toFixed(4) : 0}}</div>
          </template>
        </el-table-column>

        <el-table-column
          label="现进货总价"
          prop="purchasePriceAll"
          align="center"
          width="110"
        >
          <template slot-scope="scope">
            <div>{{ (scope.row.stock * scope.row.purchasePrice).toFixed(4) }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="进货升降总价"
          prop="purchasePriceAll"
          align="center"
          width="110"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.purchasePrice ? (scope.row.stock * scope.row.purchasePrice - scope.row.stock * scope.row.oldPurchasePrice).toFixed(4) : 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="原零售单价"
          prop="oldRetailPrice"
          align="center"
          width="110">
        </el-table-column>
        <el-table-column
          label="现零售单价"
          prop="retailPrice"
          align="center"
          width="110"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.retailPrice"
              placeholder="现零售单价"
              :disabled="disableDetails"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="原零售总价"
          prop="purchasePriceAll"
          align="center"
          width="110"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.stock ? (scope.row.stock * scope.row.oldRetailPrice).toFixed(4) : 0 }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="现零售总价"
          prop="purchasePriceAll"
          align="center"
          width="110">
          <template slot-scope="scope">
            <div>{{ (scope.row.stock * scope.row.retailPrice).toFixed(4) }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="零售升降总价"
          prop="purchasePriceAll"
          align="center"
          width="110">
          <template slot-scope="scope">
            <div>
              {{
                scope.row.stock
                  ? (scope.row.stock * scope.row.retailPrice -
                    scope.row.stock * scope.row.oldRetailPrice).toFixed(4)
                  : 0
              }}
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="BtnState === 0||BtnState === 1"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>

          <el-button @click="handleUpdataKeeping" v-if="BtnState === 2"
            >记 账</el-button
          >
          <el-button @click="handleOff" v-if="BtnState === 4">冲销</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTrimPrice,
  getTrimPrice,
  delTrimPrice,
  addTrimPrice,
  updateTrimPrice,
  exportTrimPrice,
  updataKeeping,
} from "@/api/drugs/modifyPrice";

import { sumStock } from "@/api/inventory/modifyPrice";
import { listDrugs } from "@/api/drugs/drugs";
import { listSpecs } from "@/api/drugs/specs";
import { listPrice } from "@/api/drugs/price";
import { oneList } from "@/api/inventory/inventory";

import selectTable from '@/components/selectTable/selectTable.vue'
export default {
  name: "TrimPrice",
  components: {
    selectTable
  },
  data() {
    return {
      unitArr: [],
      billOptions: [
        { dictLabel: "制单", dictValue: "1" },
        { dictLabel: "记账", dictValue: "2" },
      ],
      disableDetails: false,
      BtnState: null,
      tableId: null,
      drugsTypeOptions: [],
      unitOptions: [],
      // 子表选中数据
      checkedWarehouseDetail: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 统一调价(整体)表格数据
      TrimPriceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //添加详情
      trimPriceDetails: [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          inventory: "",
          purchasePrice: 0,
          retailPrice: 0,
          oldPurchasePrice: 0,
          oldRetailPrice: 0,
          // approvalCode: "",
          site: "",
          // productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modifyType: null,
        modifyNumber: null,
        modifyMode: null,
        code: null,
        remarks: null,
        keepingBy: null,
        keepingTime: [],
        state: null,
        del: null,
      },
      // 表单参数
      form: {
        keepingBy: window.localStorage.getItem("userName"),
        createBy: window.localStorage.getItem("userName"),
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        modifyType: "1",
      },
      modifyTypeArr: [
        { name: "手动调价", id: "1" },
        { name: "自动调价", id: "2" },
      ],
      modifyModeArr: [
        { name: "正常调价", id: "1" },
        { name: "政策调价", id: "2" },
        { name: "其他", id: "3" },
      ],
      // 表单校验
      rules: {},
      createBy: '',
      createTime: ''
    };
  },
  created() {
    this.createBy = localStorage.getItem('userName')
    this.createTime = this.dayjs().format("YYYY-MM-DD HH:mm:ss")
    this.getDicts("unit").then((response) => {
      this.unitArr = response.data;
    });
    // this.getDicts("bill_state").then((response) => {
    //   this.billOptions = response.data;
    // });

    this.getDicts("drugs_type").then((response) => {
      this.drugsTypeOptions = response.data;
    });
    this.getDicts("unit").then((response) => {
      this.unitOptions = response.data;
    });
    this.getList();
    this.getListDrugs();
  },
  methods: {
    selectChange (data) {
      var index = data.index
      var r = data.data
      console.log(index,r)
      // return
      this.$set(this.trimPriceDetails[index], 'drugsType', String(r.drugsType))
      this.$set(this.trimPriceDetails[index], 'drugsName', r.drugsName)
      this.$set(this.trimPriceDetails[index], 'drugsId', r.drugsId)
      this.$set(this.trimPriceDetails[index], 'specsId', r.specsId)
      this.$set(this.trimPriceDetails[index], 'priceId', r.priceId)
      this.$set(this.trimPriceDetails[index], 'priceName', r.placeName)
      this.$set(this.trimPriceDetails[index], 'specsName', r.drugsSpecsName)
      this.$set(this.trimPriceDetails[index], 'markupRate', r.markupRate)
      //this.$set(this.trimPriceDetails[index], 'purchasePrice', r.markupRate*(r.wholesale||r.purchasePrice).toFixed(4))
      this.$set(this.trimPriceDetails[index], 'purchasePrice', (r.wholesale||r.purchasePrice).toFixed(4))
      this.$set(this.trimPriceDetails[index], 'oldPurchasePrice', r.wholesale||r.purchasePrice)
      this.$set(this.trimPriceDetails[index], 'oldRetailPrice', r.oldRetailPrice||r.retail||r.retailPrice)
      this.$set(this.trimPriceDetails[index], 'approvalCode', r.approvalCode)
      this.$set(this.trimPriceDetails[index], 'packingUnit', r.packingUnit)
      this.$set(this.trimPriceDetails[index], 'stock', r.inventory)
      this.$set(this.trimPriceDetails[index], "specsArr", data.result);
      console.log('this.BtnState', this.BtnState)
      if (!this.BtnState) {
        this.$set(this.trimPriceDetails[index], 'retailPrice', (r.markupRate*r.retail).toFixed(4))
      }
      //console.log(this.trimPriceDetails)
      this.$forceUpdate()
    },
    /** 表单合计 **/
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          index === 7 ||
          index === 8 ||
          index === 9 ||
          index === 10 ||
          index === 14 ||
          index === 15
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = (sums[index]-0).toFixed(4);
        } else {
          sums[index] = "/";
        }

        if (index === 11) {
          let num = [];
          data.map((item) => {
            num.push(item.stock ? item.stock * item.oldPurchasePrice : 0);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[11] = (sum-0).toFixed(4);
        }

        if (index === 12) {
          let num = [];
          data.map((item) => {
            num.push(item.stock * item.purchasePrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[12] = (sum-0).toFixed(4);
        }

        if (index === 13) {
          let num = [];
          data.map((item) => {
            num.push(
              item.stock
                ? item.stock * item.purchasePrice -
                    item.stock * item.oldPurchasePrice
                : 0
            );
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[13] = (sum-0).toFixed(4);
        }

        if (index === 16) {
          let num = [];
          data.map((item) => {
            num.push(item.stock ? item.stock * item.oldRetailPrice : 0);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[16] = (sum-0).toFixed(4);
        }

        if (index === 17) {
          let num = [];
          data.map((item) => {
            num.push(item.stock * item.retailPrice);
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[17] = (sum-0).toFixed(4);
        }

        if (index === 18) {
          let num = [];
          data.map((item) => {
            num.push(
              item.stock
                ? item.stock * item.retailPrice -
                    item.stock * item.oldRetailPrice
                : 0
            );
          });
          let sum = num.reduce(function (prev, cur, index, array) {
            return prev + cur;
          });
          sums[18] = (sum-0).toFixed(4);
        }
      });

      return sums;
    },
    /** 入库单详情添加按钮操作 */
    handleAddModifyPriceDetails() {
      let obj = {};
      obj.drugsId = "";
      obj.specsId = "";
      obj.priceId = "";
      obj.stock = "";
      obj.inventory = "";
      obj.purchasePrice = "";
      obj.retailPrice = "";
      obj.approvalCode = "";
      obj.site = "";
      obj.productionCode = "";
      obj.validTime = "";
      this.trimPriceDetails.push(obj);
    },
    /** 查询统一调价(整体)列表 */
    getList() {
      this.loading = true;
      var form = Object.assign({}, this.queryParams)
      if (form.keepingTime && form.keepingTime.length) {
        form.startTime = form.keepingTime[0]
        form.endTime = form.keepingTime[1]
      } else {
        form.startTime = ''
        form.endTime = ''
      }
      delete form.keepingTime
      listTrimPrice(form).then((response) => {
        this.TrimPriceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取药品名称
    getListDrugs() {
      listDrugs().then((res) => {
        this.drugsArr = res.rows;
      });
    },
    //通过药品名称获取药品类型
    /*handleDrugsId(e, row) {
      let newArr = this.drugsArr.filter((item) => {
        return item.id === e;
      });
      this.drugsId = e;
      this.trimPriceDetails[row.$index].drugsType = String(newArr[0].drugsType);
      this.getListSpecs(e, row.$index);

      this.trimPriceDetails[row.$index].specsId = "";
      this.trimPriceDetails[row.$index].priceId = "";
      this.trimPriceDetails[row.$index].purchasePrice = "";
      this.trimPriceDetails[row.$index].retailPrice = "";
      this.trimPriceDetails[row.$index].approvalCode = "";
      this.trimPriceDetails[row.$index].packingUnit = "";
    },
    //获取药品规格
    getListSpecs(drugsId, index) {
      listSpecs({ drugsId }).then((res) => {
        // this.specsArr = res.rows;
        // this.trimPriceDetails[row.$index].specsArr = res.rows
        this.$set(this.trimPriceDetails[index], "specsArr", res.rows);
      });
    },*/
    //通过药品规格获取
    handleSpecsId(e, row) {
      let newArr = this.trimPriceDetails[row.$index].specsArr.filter((item) => {
        return item.id === e;
      });
      this.specsId = e;
      this.trimPriceDetails[row.$index].packingUnit = String(
        newArr[0].packingUnit
      );
      this.getListPrice(e, row.$index);

      this.trimPriceDetails[row.$index].priceId = "";
      this.trimPriceDetails[row.$index].purchasePrice = "";
      this.trimPriceDetails[row.$index].retailPrice = "";
      this.trimPriceDetails[row.$index].approvalCode = "";
    },
    //获取产地
    getListPrice(specsId, index) {
      listPrice({ specsId }).then((res) => {
        this.$set(this.trimPriceDetails[index], "priceArr", res.rows);
      });
    },
    //通过药品产地获取
    handlePriceId(e, row) {
      let newArr = this.trimPriceDetails[row.$index].priceArr.filter((item) => {
        return item.id === e;
      });
      this.priceId = e;
      //console.log(e);
      // this.trimPriceDetails[row.$index].purchasePrice = newArr[0].wholesale;
      // this.trimPriceDetails[row.$index].retailPrice = newArr[0].retail;
      // this.trimPriceDetails[row.$index].productionCode =
      //   newArr[0].approvalCode;
      this.$set(
        this.trimPriceDetails[row.$index],
        "markupRate",
        newArr.length > 0 ? newArr[0].markupRate : 1.25
      );
      this.$set(
        this.trimPriceDetails[row.$index],
        "oldPurchasePrice",
        newArr.length > 0 ? newArr[0].wholesale : 0
      );
      this.$set(
        this.trimPriceDetails[row.$index],
        "oldRetailPrice",
        newArr.length > 0 ? newArr[0].retail : 0
      );
      this.trimPriceDetails[row.$index].priceId = e;
      if (
        window.localStorage.getItem("pharmacyId") &&
        this.drugsId &&
        this.specsId &&
        this.priceId
      ) {
        // this.getOneList(row.$index);
        this.getSumStock(row.$index);
      }
    },
    //获取库存数量
    getOneList(index) {
      let params = {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        drugsId: this.drugsId,
        specsId: this.specsId,
        priceId: this.priceId,
      };
      oneList(params).then((res) => {
        // this.trimPriceDetails[index].markupRate = res.data[0].markupRate;
        // this.$set(
        //   this.trimPriceDetails[index],
        //   "markupRate",
        //   res.data[0].markupRate
        // );
        // this.$set(
        //   this.trimPriceDetails[index],
        //   "oldPurchasePrice",
        //   res.data[0].purchasePrice
        // );
        // this.$set(
        //   this.trimPriceDetails[index],
        //   "oldRetailPrice",
        //   res.data[0].retailPrice
        // );
      });
    },
    //获取调配数量
    getSumStock(index) {
      let params = {
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        drugsId: this.drugsId,
        specsId: this.specsId,
        priceId: this.priceId,
      };
      sumStock(params).then((res) => {
        //console.log(res);
        res.data
          ? this.$set(this.trimPriceDetails[index], "stock", res.data.stock)
          : this.$set(this.trimPriceDetails[index], "stock", 0);
      });
    },
    /** 入库单详情删除按钮操作 */
    handleDeleteModifyPriceDetails() {
      if (this.checkedWarehouseDetail.length == 0) {
        this.msgError("请先选择要删除的入库单详情数据");
      } else {
        const trimPriceDetails = this.trimPriceDetails;
        const checkedWarehouseDetail = this.checkedWarehouseDetail;
        this.trimPriceDetails = trimPriceDetails.filter(function (item) {
          return checkedWarehouseDetail.indexOf(item.index) == -1;
        });
      }
    },
    /** 入库单详情序号 */
    rowWarehouseDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 复选框选中数据 */
    handleWarehouseDetailSelectionChange(selection) {
      this.checkedWarehouseDetail = selection.map((item) => item.index);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        modifyType: "1",
        modifyNumber: null,
        modifyMode: null,
        code: null,
        remarks: null,
        createBy: null,
        createTime: null,
        keepingBy: null,
        keepingTime: null,
        state: null,
        del: null,
      };
      this.trimPriceDetails = [
        {
          drugsId: "",
          specsId: "",
          riceId: "",
          stock: "",
          inventory: "",
          purchasePrice: "",
          oldRetailPrice: '',
          oldPurchasePrice: '',
          retailPrice: "",
          // approvalCode: "",
          site: "",
          // productionCode: "",
          validTime: "",
          specsArr: [],
          priceArr: [],
        },
      ];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.form.code = new Date().getTime();
      this.form.code = this.dayjs().format("YYYYMMDDHHmmssSSS");
      // this.form.createTime = new Date();
      // this.form.keepingTime = new Date();
      this.disableDetails = false;
      this.open = true;
      this.title = "添加统一调价";
      this.BtnState = 0;
    },
    /** 记账 **/
    handleUpdataKeeping() {
      updataKeeping(this.tableId).then((res) => {
        this.msgSuccess("记账成功");
        this.open = false;
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(num, row) {
      this.reset();
      this.BtnState = num;
      const id = row.id || this.ids;
      this.tableId = id;
      getTrimPrice(id).then((response) => {
        response.data.trimPriceDetails.map((item) => {
          item.drugsType = String(item.drugsType);
          item.packingUnit = String(item.packingUnit);
        });
        this.form = response.data;
        this.trimPriceDetails = response.data.trimPriceDetails;
        this.open = true;
      });
      if (num === 3 || num === 2) {
        this.disableDetails = true;
      } else {
        this.disableDetails = false;
      }
      num === 1
        ? (this.title = "修改统一调价")
        : num === 2
        ? (this.title = "记账统一调价")
        : num === 3
        ? (this.title = "统一调价详情")
        : "";
    },
    formatTime(date, fmt) {
      var date = new Date(date);
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      var o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
      };
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          var str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
          );
        }
      }
      return fmt;
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.form.modifyMode) {
        return this.$message.warning('请选择调价方式')
      }
      //console.log(this.trimPriceDetails.find(v => v.retailPrice === '' || v.purchasePrice === ''))
      if (this.trimPriceDetails.find(v => v.retailPrice === '' || v.purchasePrice === '')) {
        return this.$message.warning('请完善现进货单价和现零售单价')
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.trimPriceDetails = this.trimPriceDetails;
          // this.form.createTime = this.formatTime(
          //   this.form.createTime,
          //   "yyyy-MM-dd hh:mm:ss"
          // );
          // this.form.keepingTime = this.form.keepingTime
          //   ? this.formatTime(this.form.keepingTime, "yyyy-MM-dd hh:mm:ss")
          //   : null;
          if (this.form.id != null) {
            updateTrimPrice(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrimPrice(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("确定需要删除已选数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delTrimPrice(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有统一调价(整体)数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportTrimPrice(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
