<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      :title="type === 'add' ? `新增${typeText}` : `编辑${typeText}`"
      :form="form"
      :rules="rules"
      @submit="submit"
    >
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">{{ typeText }}事项 ：</div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.name"
              style="width: 300px"
              :placeholder="'请填写' + typeText + '事项'"
            ></el-input>
          </div>
        </div>
      </template>
      <template v-slot:report_type v-if="outcomeType == 2">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >
            报销类型 ：
          </div>
          <div class="xy-table-item-content">
            <el-select
              v-model="form.report_type"
              clearable
              placeholder="请选择报销类型"
              style="width: 300px"
            >
              <el-option
                v-for="item in report_types"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:other_type v-if="outcomeType == 3">
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >
            其他支出类型 ：
          </div>
          <div class="xy-table-item-content">
            <el-select
              v-model="form.other_type"
              clearable
              placeholder="请选择其他支出类型"
              style="width: 300px"
            >
              <el-option
                v-for="item in other_types"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">{{ typeText }}金额 ：</div>
          <div class="xy-table-item-content">
            <el-input-number
              v-model="form.money"
              clearable
              placeholder="请输入报销金额"
              style="width: 300px"
              :controls="false"
            ></el-input-number>
          </div>
        </div>
      </template>
      <template #remark>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            备注
          </div>
          <div class="xy-table-item-content">
            <el-input style="width: 300px" type="textarea" v-model="form.remark" :autosize="{ minRows: 2 }"></el-input>
          </div>
        </div>
      </template>
      <template #files>
        <div class="xy-table-item">
          <div class="xy-table-item-label">文件 ：</div>
          <div class="xy-table-item-content">
            <el-upload
              style="width: 300px"
              ref="upload"
              multiple
              :headers="{
                'Authorization':'Bearer ' + getToken()
              }"
              :on-success="successHandle"
              :before-upload="uploadBefore"
              accept="application/x-rar-compressed,application/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf"
              :action="action"
              :file-list="fileList"
              :auto-upload="false"
              :on-remove="removeHande"
            >
              <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
              >
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="$refs['upload'].submit()"
              >开始上传</el-button
              >
              <div slot="tip" class="el-upload__tip">
                支持文件格式：.rar .zip .doc .docx .pdf
                <br />单个文件不能超过500kb
              </div>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:oa>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >关联审批单
          </div>
          <div class="xy-table-item-content">
            <div
              class="contract-add-plan"
              style="width: 300px"
              @click="showPlan"
            >
              <template v-if="form.oa.length > 0">
                <template v-for="item in form.oa">
                  <Tag closable color="primary" @on-close="delOa(item)">{{
                    item.title
                  }}</Tag>
                </template>
              </template>
              <template v-else>
                <div class="contract-add-plan-no-plan">请选择关联审批单</div>
              </template>
            </div>
          </div>
        </div>
      </template>
    </xy-dialog>

    <!--  新增表 预算计划  -->
    <xy-dialog
      :is-show.sync="isShowPlan"
      :width="820"
      title="审批单"
    >
      <template>
        <xy-table
          ref="planTable"
          :height="300"
          :list="plans"
          row-key="id"
          :show-index="false"
          :table-item="planTable"
          style="margin-top: 10px"
          @select="selected"
        >
          <template v-slot:btns>
          </template>
        </xy-table>

        <div style="display: flex; justify-content: flex-end">
          <Page
            :total="planTotal"
            show-elevator
            @on-change="e => {planSearch.p = e; getBudgets()}"
          />
        </div>
      </template>

      <template v-slot:footerContent>
        <Button type="primary" @click="isShowPlan = false">确定</Button>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import { getparameter } from "@/api/system/dictionary";
import {
  addContrant,
  editorContract,
  detailContract as show,
} from "@/api/contract/contract";
import { httpCurl } from "@/api/out"
export default {
  props: {
    report_types: {
      type: Array,
      default: () => [
        {
          value: "医药报销支出",
          id: 1,
        },
        {
          value: "出差报销支出",
          id: 2,
        },
      ],
    },
    other_types: {
      type: Array,
      default: () => [],
    },
    departments: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      moneyWay: [],
      plans: [],
      planTotal: 0,
      isShowPlan: false,
      planSearch: {
        mod_name: '出差审批',
        list_rows: 10,
        p: 1
      },
      planTable: [
        {
          width: 46,
          sortable: false,
          type: "selection",
          fixed: "left",
          reserveSelection: true
        },
        {
          label: '名称',
          prop: 'title',
          minWidth: 160,
          fixed: 'left'
        },
        {
          label: '部门',
          prop: 'dept_name',
          width: 180
        },
        {
          label: '人员',
          prop: 'emp_name',
          width: 140
        },
        {
          label: '创建时间',
          prop: 'create_time',
          width: 180,
          formatter: (cell,data,value)=> {
            return this.$moment(new Date(Number(value)*1000)).format('YYYY-MM-DD')
          }
        }
      ],

      isShow: false,
      id: "",
      type: "",

      fileList: [],
      action: process.env.VUE_APP_UPLOAD_API,
      form: {
        name: "",
        outcome_type: "",
        report_type: "",
        other_type: "",
        money: undefined,
        files: [],
        remark: "",
        oa: [],
      },
      rules: {
        report_type: [
          {
            required: true,
            message: "请填写报销类型",
          },
        ],
        other_type: [
          {
            required: true,
            message: "请填写其他支出类型",
          },
        ],
      },
    };
  },
  methods: {
    getToken,
    //上传
    successHandle(response, file, fileList) {
      this.fileList = fileList;
    },
    removeHande(file, fileList) {
      this.fileList = fileList;
    },
    uploadBefore(file) {
      console.log(file);
      if (file.size / 1000 > 500) {
        this.$message({
          type: "warning",
          message: "上传文件大小超过500kb！",
        });
        return false;
      }
    },

    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    async getDetail() {
      const res = await show({ id: this.id });
      this.$integrateData(this.form, res);
      this.fileList = res.files_detail.map(i =>  {
        return {
          url: i.url,
          name: i.original_name,
          response: i
        }
      })
    },

    submit() {
      this.form.outcome_type = this.outcomeType;
      this.form.files = this.fileList.map(i => i.response?.id);
      if (this.type === "add") {
        if (this.form.hasOwnProperty("id")) {
          delete this.form.id;
        }
        addContrant(this.form).then((res) => {
          this.$message({
            type: "success",
            message: this.type === "add" ? "新增支出" : "编辑支出" + "成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
      if (this.type === "editor") {
        Object.defineProperty(this.form, "id", {
          value: this.id,
          enumerable: true,
          configurable: true,
          writable: true,
        });

        editorContract(this.form).then((res) => {
          this.$message({
            type: "success",
            message: this.type === "add" ? "新增支出" : "编辑支出" + "成功",
          });
          this.isShow = false;
          this.$emit("refresh");
        });
      }
    },

    selected (rows) {
      this.form.oa = rows.map(i => {
        return {
          id: i.id,
          title: i.title
        }
      })
    },
    delOa (item) {
      this.form.oa.splice(this.form.oa.indexOf(this.form.oa.find(i => item.id === i.id)),1)
    },

    //获取资金渠道
    async getMoneyWay() {
      this.moneyWay = (
        await getparameter({
          number: "money_way",
        })
      ).detail;
    },
    async showPlan() {
      await this.getBudgets();
      this.isShowPlan = true;
    },
    //获取预算计划
    async getBudgets() {
      let res = await httpCurl(this.planSearch, false, '/Api/flowList');
      this.plans = res.list
      this.planTotal = Number(res.total)

      this.plans.forEach(i => {
        if (this.form.oa.find(oa => oa.id === i.id)) {
          this.$refs['planTable'].toggleRowSelection(i)
        }
      })
    },

  },
  computed: {
    outcomeType() {
      return this.$route.path.split("_")[1];
    },
    typeText() {
      let type = this.$route.path.split("_")[1];
      if (type == 2) {
        return "报销";
      }
      if (type == 3) {
        return "其他支出";
      }
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        if (this.type === "editor") {
          this.getDetail();
        }
      } else {
        this.id = "";
        this.type = "";
        this.init();
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },

  },
  created() {
    this.getMoneyWay();
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
.xy-table-item-label {
  width: 158px;
}
.contract-add-plan {
  min-height: 30px;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  align-content: center;

  padding: 0 8px;

  &-no-plan {
    height: 30px;
    line-height: 30px;
    color: #cdd0d5;
  }
}

.slot-btns {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: flex-start;

  &-item {
    margin: 0 6px 4px 0;
  }
}
</style>
