<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="600px"
    append-to-body
    draggable
    @close="close"
  >
    <div style="padding: 8px 24px 16px 24px" v-if="visible">
      <el-form
        size="small"
        ref="priceListRef"
        label-width="100px"
        :model="form"
        :rules="rules"
      >
        <el-col>
          <el-form-item label="注册省市区：" required prop="provinceCode">
            <el-select
              v-model="form.provinceCode"
              placeholder="省份"
              style="width: 33.33%"
              @change="handleSelectProvince"
            >
              <el-option
                v-for="item in provinces"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="form.cityCode"
              placeholder="城市"
              style="width: 33.33%"
              @change="handleSelectCity"
            >
              <el-option
                v-for="item in cities"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
            <el-select
              v-model="form.districtCode"
              placeholder="行政区"
              style="width: 33.33%"
              @change="handleSelectDistrict"
            >
              <el-option
                v-for="item in districts"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="选择任务：" prop="taskTypeId">
              <el-select
                v-model="form.taskTypeId"
                type="text"
                placeholder="选择任务"
                :clearable="true"
                width="100px"
                @change="handleTaskChange"
                @clear="handleDetailClear"
              >
                <el-option
                  v-for="item in taskType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="选择变更类型"
              prop="alterType"
              v-if="form.taskTypeId != null && form.taskTypeId == 6"
            >
              <el-select
                v-model="form.alterType"
                type="text"
                placeholder="选择变更类型"
                :clearable="true"
                width="100px"
                @clear="handleTaskDetaiClear"
              >
                <el-option
                  v-for="item in alterTypeDetail"
                  :key="item.id"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="单价"
              prop="price"
              v-if="form.taskTypeDetailId != null"
            >
              <el-input
                v-model="form.price"
                width="100px"
                placeholder="请输入单价"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="选择任务明细"
              prop="taskTypeDetailId"
              v-if="form.taskTypeId != null"
            >
              <el-select
                v-model="form.taskTypeDetailId"
                type="text"
                placeholder="选择任务明细"
                :clearable="true"
                width="100px"
                @clear="handleTaskDetaiClear"
              >
                <el-option
                  v-for="item in taskTypeDetail"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              label="备注"
              prop="remark"
              v-if="form.taskTypeDetailId != null"
            >
              <el-input type="textarea" rows="2" v-model="form.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          icon="Finished"
          size="small"
          >确 定</el-button
        >
        <el-button icon="close" size="small" @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
    

  
<script setup>
import { getPriceList, getTenantList } from "@/api/system/priceList";
import { alterTypeDetail } from "@/utils/default";
import {
  listOncePrice,
  delOncePrice,
  getTaskTypeList,
  getTaskTypeDetailList,
  addOncePrice,
  updateOncePrice,
} from "@/api/system/oncePrice";
const { proxy } = getCurrentInstance();
/** 字典数组区 */
/** 表单抽屉 页变量 */
const title = ref("");
const loading = ref(false);
const multiple = ref(true);
const visible = ref(false);
const editStatus = ref(true);
const provinces = ref(proxy.region.getProvinces());
provinces.value.unshift({ code: "", name: "全部" });
const cities = ref([]);
const districts = ref([]);
/** 甲方租户 */
const firstParty = ref("");
/** 乙方租户 */
const secondParty = ref("");
const isFullscreen = ref(false);
/** 任务类型 */
const taskType = ref([]);
/** 任务类型明细 */
const taskTypeDetail = ref({});
const webHost = import.meta.env.VITE_APP_BASE_API;
/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});

const data = reactive({
  form: {},
  rules: {
    taskTypeDetailId: [
      {
        required: true,
        message: "请选择任务明细",
        trigger: "blur",
      },
    ],

    alterType: [{ required: true, message: "请选择变更类型", trigger: "blur" }],
    taskTypeId: [
      { required: true, message: "请选择任务类型", trigger: "blur" },
    ],
    price: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    annualIncome: [
      { required: true, message: "年收入不能为空", trigger: "blur" },
    ],
    toAccountName: [
      { required: true, message: "乙方不能为空", trigger: "blur" },
    ],
    fromAccountName: [
      { required: true, message: "甲方不能为空", trigger: "blur" },
    ],
    provinceCode: [{ validator: areaValidator, trigger: "blur" }],
    isChanged: [
      {
        required: true,
        message: "是否变更不能为空",
        trigger: "blur",
      },
    ],
  },
});

const { getList } = toRefs(props);
const { form, rules } = toRefs(data);
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(id, row) {
  reset();
  visible.value = true;

  console.log("打开", row);
  getTaskTypeList().then((res) => {
    taskType.value = res.data;
  });

  if (id) {
    getPriceList(id).then((response) => {
      console.log(response);
      form.value = response.data;
      title.value = "修改价目信息";
      console.log(form.value);
      handleTaskChange(form.value.taskTypeId);
      initRegion();
    });
  } else {
    title.value = "添加价目信息";
  }
}

/** 任务切换事件 */
function handleTaskChange(item) {
  if (item) {
    getTaskTypeDetailList(item).then((res) => {
      taskTypeDetail.value = res.data;
    });
  } else {
    taskTypeDetail.value = [];
  }
}

/** 取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

/** 省市区验证 */
function areaValidator(rule, value, callback) {
  if (!form.value.provinceCode) {
    callback(new Error("省份不能为空"));
    return;
  }
  if (!form.value.cityCode) {
    callback(new Error("城市不能为空"));
    return;
  }
  if (!form.value.districtCode) {
    callback(new Error("行政区不能为空"));
    return;
  }
  console.log(form.value);
  return callback();
}

/** 清除选择任务  */
function handleTaskClear() {
  form.value.taskTypeId = null;
}

/** 初始化地区 */
function initRegion() {
  cities.value = proxy.region.getCities(form.value.provinceCode);
  cities.value.unshift({ code: "", name: "全部" });
  districts.value = proxy.region.getDistricts(form.value.cityCode);
  districts.value.unshift({ code: "", name: "全部" });
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    price: null,
    taskTypeId: null,
    annualIncome: "",
    isChanged: null,
    fromTenantId: null,
    toTenantId: null,
    remark: null,
    createTime: null,
    creatorId: null,
    updateTime: null,
    updaterId: null,
    deleted: null,
    version: null,
    toAccountName: "",
    fromAccountName: "",
  };
  proxy.resetForm("priceListRef");
}

/** 输入框输出建议 */
const querySearchAsync = (queryString, cb) => {
  const query = { accountName: queryString };
  getTenantList(query).then((res) => {
    cb(res.data);
  });
};

/** 乙方租户选择 */
function handleSecondPartySelect(item) {
  form.value.toTenantId = item.id;
  form.value.toAccountName = item.accountName;
}

/** 甲方租户选择 */
function handleFirstPartySelect(item) {
  form.value.fromTenantId = item.id;
  form.value.fromAccountName = item.accountName;
}

/** 提交按钮 */
function submitForm() {
  console.log(proxy.$refs["priceListRef"].validate());
  proxy.$refs["priceListRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateOncePrice(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          visible.value = false;
          getList.value();
        });
      } else {
        addOncePrice(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          visible.value = false;
          getList.value();
        });
      }
    }
  });
}

function handleSelectProvince() {
  const _provinceCode = form.value.provinceCode;
  const _province = provinces.value.find(function (item) {
    return item.code === _provinceCode;
  });
  form.value.province = _province.name;
  cities.value = proxy.region.getCities(_provinceCode);
  if (cities.value.length === 0) {
    // 清空城市数据
    form.value.cityCode = "";
    form.value.city = "";
    cities.value = [{ code: "", name: "全部" }];
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [];
  } else {
    cities.value.unshift({ code: "", name: "全部" });
    form.value.cityCode = cities.value[0].code;
    form.value.city = cities.value[0].name;
    handleSelectCity();
  }
}

function handleSelectCity() {
  const _cityCode = form.value.cityCode;
  const _city = cities.value.find(function (item) {
    return item.code === _cityCode;
  });
  form.value.city = _city.name;
  districts.value = proxy.region.getDistricts(_cityCode);
  if (districts.value.length === 0) {
    // 清空行政区数据
    form.value.districtCode = "";
    form.value.district = "";
    districts.value = [{ code: "", name: "全部" }];
  } else {
    districts.value.unshift({ code: "", name: "全部" });
    form.value.districtCode = districts.value[0].code;
    form.value.district = districts.value[0].name;
  }
}

function handleSelectDistrict() {
  const _districtCode = form.value.districtCode;
  const _district = districts.value.find(function (item) {
    return item.code === _districtCode;
  });
  form.value.district = _district.name;
}

/** 查询表单信息  */
function getForm() {
  loading.value = true;
  getPriceList(form.value.id).then((response) => {
    loading.value = false;
    form.value = response.data;
  });
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
  