<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        v-model="form"
        :page="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-position"
            @click="distribute(scope.row)"
            >分配
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 0"
            type="text"
            size="small"
            icon="el-icon-sold-out"
            @click="updateTy(scope.row, scope.index)"
            >下架
          </el-button>
          <el-button
            v-if="scope.row.enableFlag == 1"
            type="text"
            size="small"
            icon="el-icon-sell"
            @click="updateQy(scope.row, scope.index)"
            >上架
          </el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-sell"
            @click="bindQuestionnaireFn(scope.row, scope.index)"
            >绑定问卷
          </el-button>
        </template>

        <template slot-scope="scope" slot="drugEntNum">
          <span v-show="scope.row.drugEntNum > 0">
            <!--                 <el-tag></el-tag>-->
            <!--                <el-link type="success">{{scope.row.drugEntNum}}</el-link>-->
            <el-button type="text" @click="lookD(scope.row)">{{
              scope.row.drugEntNum
            }}</el-button>
          </span>
        </template>

        <template slot="drugEntNameSearch">
          <el-select
            v-model="searchForm.drugEntName"
            allow-create
            filterable
            placeholder="请选择生产企业"
          >
            <el-option
              v-for="item in drugEntList"
              :key="item.id"
              :label="item.entname"
              :value="item.entname"
            ></el-option>
          </el-select>
        </template>

        <template slot="drugEntNameForm">
          <el-select
            v-model="form.drugEntName"
            allow-create
            clearable
            filterable
            placeholder="生产企业"
          >
            <el-option
              v-for="item in drugEntList"
              :key="item.id"
              :label="item.entname"
              :value="item.entname"
            ></el-option>
          </el-select>
        </template>
        <template slot="doseNameForm">
          <el-select
            v-model="form.doseName"
            allow-create
            clearable
            filterable
            placeholder="剂型"
          >
            <el-option
              v-for="item in doseList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>
        <template slot="guigeNameForm">
          <el-select
            v-model="form.guigeName"
            allow-create
            clearable
            filterable
            placeholder="规格"
          >
            <el-option
              v-for="item in guigeList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </template>

        <template slot="ssxkcyyForm">
          <el-select
            v-model="form.ssxkcyy"
            allow-create
            clearable
            filterable
            placeholder="上市许可持有人"
          >
            <el-option
              v-for="item in drugEntList"
              :key="item.id"
              :label="item.entname"
              :value="item.entname"
            ></el-option>
          </el-select>
        </template>
      </avue-crud>

      <el-dialog
        title="分配"
        :visible.sync="showDialog"
        width="60%"
        @close="handleClose"
        center
      >
        <el-form
          :model="form"
          :rules="rules"
          ref="drugForm"
          label-width="138px"
          class="demo-ruleForm"
        >
          <el-form-item label="积分包名称：" prop="drugname">
            <el-input disabled v-model="form.drugname"></el-input>
          </el-form-item>
          <el-form-item label="通用名称：" prop="drugnameTy">
            <el-input disabled v-model="form.drugnameTy"></el-input>
          </el-form-item>
          <el-form-item label="生产企业：" prop="drugEntName">
            <el-input disabled v-model="form.drugEntName"></el-input>
          </el-form-item>
          <el-form-item label="推广企业：" prop="reDeptList" required>
            <el-select
              multiple
              style="width: 100%"
              :disabled="reDeptDisabled"
              v-model="form.reDeptList"
              filterable
              placeholder="推广企业"
            >
              <el-option
                v-for="item in deptList"
                :key="item.deptId"
                :label="item.name"
                :value="item.deptId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose" icon="el-icon-close">关 闭</el-button>
          <el-button
            v-if="distributeType"
            type="primary"
            :loading="buttonLoading"
            icon="el-icon-check"
            @click="drugSubmit('drugForm')"
            >提 交</el-button
          >
        </span>
      </el-dialog>
    </basic-container>
    <!-- 绑定问卷 -->
    <bindQuestionnaireDialog
      ref="bindQuestionnaireRef"
      @success="bindQuestionnairSuccess"
    />
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  distribute,
  listDept,
  listReDept
} from "@/api/wmdadrugentdrugtable";
import { tableOption } from "@/const/crud/wmdadrugentdrugtable";
import { mapGetters } from "vuex";
import { drugEntList } from "@/api/wmdadrugent";
import { getDictType } from "@/api/common";
import bindQuestionnaireDialog from "./bindQuestionnaireDialog.vue";

export default {
  name: "wmdadrugentdrugtable",
  components: { bindQuestionnaireDialog },
  data() {
    return {
      distributeType: false,
      buttonLoading: false,
      rules: {
        reDeptList: [
          { required: true, message: "请选择推广企业", trigger: "change" }
        ]
      },
      showDialog: false,
      form: {},
      drugEntList: [],
      doseList: [],
      guigeList: [],
      deptList: [],
      reDeptDisabled: false,
      wmdadrugentOptions: [],
      wmdadrugentProps: {
        label: "entname",
        value: "id"
      },
      defaultProps: {
        label: "entname",
        value: "id"
      },
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.admin_wmdadrugentdrugtable_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.admin_wmdadrugentdrugtable_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.admin_wmdadrugentdrugtable_edit,
          false
        )
      };
    }
  },
  created() {
    drugEntList().then(response => {
      this.wmdadrugentOptions = response.data.data;
      this.drugEntList = response.data.data;
    });
    listDept().then(response => {
      this.deptList = response.data.data;
    });
    getDictType({ type: "dose" }).then(res => {
      this.doseList = res.data.data;
    });
    getDictType({ type: "guige" }).then(res => {
      this.guigeList = res.data.data;
    });
  },
  methods: {
    bindQuestionnaireFn(row) {
      console.log("row", row);
      this.$refs.bindQuestionnaireRef.showInfo(row.id);
    },
    bindQuestionnairSuccess() {
      this.getList(this.page);
    },
    lookD(obj) {
      this.form = obj;
      listReDept({ id: obj.id }).then(response => {
        this.form.reDeptList = response.data.data.map(item => Number(item));
        this.reDeptDisabled = true;
        this.showDialog = true;
      });
    },
    drugSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          const args = {
            reDeptList: this.form.reDeptList,
            id: this.form.id
          };

          distribute(args)
            .then(() => {
              this.$message.success("分配成功");
              this.getList(this.page, this.searchForm);
              this.buttonLoading = false;
              this.handleClose();
            })
            .catch(() => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      this.form = {};
      this.showDialog = false;
      this.distributeType = false;
      this.reDeptDisabled = false;
    },
    distribute(obj) {
      this.form = obj;
      this.distributeType = true;
      listReDept({ id: obj.id }).then(response => {
        this.form.reDeptList = response.data.data.map(item => Number(item));
        this.showDialog = true;
      });
    },
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function(row, index, done, loading) {
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    updateTy: function(row, index, done, loading) {
      row.enableFlag = "1";
      putObj(row)
        .then(data => {
          this.$message.success("下架成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    updateQy: function(row, index, done, loading) {
      row.enableFlag = "0";
      putObj(row)
        .then(data => {
          this.$message.success("上架成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      console.log(this.searchForm);
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    }
  }
};
</script>
