<script>
import {drugsMapUpdate} from "@/api/drugs/drugs";


export default {
  components: {
    // 'v-selectpage': SelectPage
  },
  props: {
    communityId: {type: [String, Number], required: true},
    mechanismId: {type: [String, Number], required: true},
  },
  data() {
    return {
      dataset: [],
      searchTableForSystemColumns: [
        {title: "名称", data: "drugsName"},
        {title: "编码", data: "drugsId"},
        {title: "规格", data: "drugsSpecsName"},
        {title: "产地", data: "placeName"},
        {title: "零售价", data: "retail"},
      ],
      searchTableForMechanismColumns: [
        {title: "名称", data: "herbsName"},
        {title: "编码", data: "herbsCode"},
        {title: "规格", data: "specsName"},
        {title: "产地", data: "placeName"},
      ],

      editSystem: -1,
      editMechanism: -1,
    }
  },
  computed: {
    tableHeight() {
      return Math.min(Math.floor(window.innerHeight * 0.6), 598 + 2);
    },
    selected() {
      return this.dataset.filter(item => item && item.drugsId && item.herbsId);
    },
  },
  mounted() {
    const dataset = Array.from({length: 1 - this.dataset.length});
    for (const _ of dataset) this.append();
  },
  methods: {
    append(model) {
      this.dataset.push(model || {});
    },
    handleDelete(row, index) {
      this.dataset.splice(index, 1);
    },
    tableSpanMethod({row, column, rowIndex, columnIndex}) {
      if (column.type === 'index' || column.label === '操作') return [1, 1];

      if (columnIndex === 1) return row.drugsName ? [1, 1] : [1, 2];
      if (columnIndex === 2) return row.drugsName ? [1, 1] : [0, 0];
      if (columnIndex === 3) return row.herbsName ? [1, 1] : [1, 4];
      return row.herbsName ? [1, 1] : [0, 0];
    },
    async handle() {
      if (!this.selected.length) return this.msgInfo('请至少填写一条数据');

      const index = this.dataset.findIndex(item => (item.drugsId && !item.herbsId) || (item.herbsId && !item.drugsId));
      if (index !== -1) return this.msgInfo(`第 ${index + 1} 行数据请补充完整`);

      try {
        const {msg = '创建成功'} = await drugsMapUpdate(this.selected, {
          communityId: this.communityId,
          mechanismId: this.mechanismId,
        })
        this.msgSuccess(msg);
        this.$emit('close', true);
      } catch (error) {}
    },
    cancel() {
      this.$emit('close', false);
    },


    searchTableFormat(res) {
      try {
        if (res.rows) return {totalRow: res.total, list: res.rows};
        else return {totalRow: res.data.length, list: res.data};
      } catch (error) { return {totalRow: 0, list: []} }
    },
    selectSystem([value], row, index) {
      if (value) {
        row.drugsId = value.drugsId;
        row.drugsName = value.drugsName;
        row.drugsPriceId = value.priceId;
        row.drugsSpecsId = value.specsId;
        row.drugsSpecsName = value.drugsSpecsName;
        row.drugsPlaceId = value.placeId;
        row.drugsPlaceName = value.placeName;
      } else {
        delete row.drugsId;
        delete row.drugsName;
        delete row.drugsPriceId;
        delete row.drugsSpecsId;
        delete row.drugsSpecsName;
        delete row.drugsPlaceId;
        delete row.drugsPlaceName;
        this.dataset.splice(index, 1, row);
      }
      if (row.drugsId && row.herbsId) this.append();
      this.editSystem = -1;
    },
    selectMechanism([value], row, index) {
      if (value) {
        row.herbsId = value.id;
        row.herbsCode = value.herbsCode;
        row.herbsName = value.herbsName;
        row.herbsSpecsCode = value.specsCode;
        row.herbsSpecsName = value.specsName;
        row.herbsPlaceCode = value.placeCode;
        row.herbsPlaceName = value.placeName;
      } else {
        delete row.herbsId;
        delete row.herbsCode;
        delete row.herbsName;
        delete row.herbsSpecsCode;
        delete row.herbsSpecsName;
        delete row.herbsPlaceCode;
        delete row.herbsPlaceName;
        this.dataset.splice(index, 1, row);
      }
      if (row.drugsId && row.herbsId) this.append();
      this.editMechanism = -1;
    },
  },
}
</script>

<template>
  <div class="wrapper">
    <el-table :data="dataset" style="width: 100%;" :height="tableHeight" stripe :span-method="tableSpanMethod">
      <el-table-column type="index" width="55" align="center" label="序号" fixed/>
      <el-table-column label="系统药品" align="center">
        <el-table-column prop="drugsName" label="名称" align="center">
          <template slot-scope="scope">
            <template v-if="scope.$index === editSystem || !scope.row.drugsId">
              <v-selectpage :tb-columns="searchTableForSystemColumns"
                            key-field="drugsId" v-model="scope.row.drugsId"
                            placeholder="请输入系统药品名称" title="系统药品"
                            data="drugsSearchForSystem" :params="{}" :pagination="false"
                            :result-format="searchTableFormat"
                            @values="selectSystem($event, scope.row, scope.$index)"
              ></v-selectpage>
            </template>
            <a v-else>
              {{ scope.row.drugsName }}
              <i class="icon el-icon-circle-close" @click="selectSystem([], scope.row, scope.$index)"></i>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="drugsId" label="编码" align="center"></el-table-column>
      </el-table-column>
      <el-table-column label="医疗机构药品" align="center">
        <el-table-column prop="herbsName" label="名称" align="center">
          <template slot-scope="scope">
            <template v-if="scope.$index === editMechanism || !scope.row.herbsId">
              <v-selectpage :tb-columns="searchTableForMechanismColumns"
                            key-field="id" v-model="scope.row.herbsId"
                            placeholder="请输入医疗机构药品名称" title="医疗机构药品"
                            data="drugsSearchForMechanism" :params="$props" :pagination="true"
                            :result-format="searchTableFormat"
                            @values="selectMechanism($event, scope.row, scope.$index)"
              ></v-selectpage>
            </template>
            <a v-else>
              {{ scope.row.herbsName }}
              <i class="icon el-icon-circle-close" @click="selectMechanism([], scope.row, scope.$index)"></i>
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="herbsCode" label="编码" align="center"></el-table-column>
        <el-table-column prop="herbsSpecsName" label="规格" align="center"></el-table-column>
        <el-table-column prop="herbsSpecsCode" label="规格编码" align="center"></el-table-column>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button style="width: 40px;" type="danger" size="mini"
                     :disabled="Object.keys(scope.row).length === 0"
                     @click="handleDelete(scope.row, scope.$index)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="el-dialog__footer">
      <el-button type="primary" @click="handle" :disabled="selected.length === 0">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.icon {
  margin-top: 6px;
  float: right;

  &:hover {
    color: #00afff;
  }
}
</style>
